Getting Started with React Hooks

Kamesh Kumar Singh
2 min readApr 27, 2020

React Hooks is added newly in React 16.8 which lets us use state and other features without writing the class based components. We’ll be seeing the side by side comparison of React Hooks and Class based states along with the examples.

For ease of understanding, we’ll be taking a counter example which increments the value of a counter once the button is clicked.

State in Class Based Component:

First, let’s see how we do it using the class based components with which you are already familiar.

State in Class-based components

The useState Hook:

Now, let’s go ahead and have a look at the useState hook in practical. Using this hook makes it quite easier to write the code and better understand it.

The useState Hook

Now, let’s understand the useState hook.

const [count , setCount]= useState(0);

useState method accepts the initial value of the variable and returns two values. In above example we have taken count and setCount. Let’s understand this from the picture given below:

Now that we have written the useState hook, it’s time to use in the button in order to increment it. Unlike class based components, we’ll have to write an arrow function in the onClick property. so this is how we do it:

<button onClick={() => setCount(count + 1)}>Count {count}</button>

Now I hope you’ve a pretty good idea of the useState hook. Go ahead and hit your fingers on the keyboard and play with hooks.

--

--