React Hooks are a new addition in React, it helps us to use state without writing classes.
I.e we can use state in the functional component also.
Rules of Hooks
We can only call Hooks at the top level, its cannot be called inside loops, conditions or nested functions.
From the component
When do we use Hooks
If we write a function component and we want to use state inside our function component we had to convert it into a class component to be able to use state, but now with the help of hooks we can use state in the function component with converting it into a class component.
Declaring state variable
By calling useState we declare our variables, Here “count” is our state variable and setCount is the state.
Using State Hooks
This is an example of useState, This is how a functional component looks like when using hooks.
The Equivalent class component will look something like this
When want to display the value of state variable
When using Hooks
- When using Hooks
Hooks have benefited us with the following:
How we managing state has become easier to reason about
Our code is significantly simplified, and more readable
It’s easier to extract and share stateful logic in our apps.