Getting Started with React Hooks .

Getting Started with React Hooks .


4 min read

Hooks In ReactJs

Hello Everyone ! Lets learn react hooks today..

So first thing first ,

What the hack is hooks ? ๐Ÿค”

A Hook is actually function that lets you โ€œhook intoโ€ React features. If we take an example of useState() so it basically lets you define state inside the functional component.

Hooks are the new addition to react library from react 16.8.

Now Why should I use hooks ? ๐Ÿค”

So when you writing a functional component and you got a feel that I need a state . Now in functional component you can't declare a state inside the functional component . So there comes the use of hooks . There are number of hooks in Reactjs , this is just one example of useState hook.

Rules to declare the hooks :

  • Hooks lie at the top right in component or must be declare at the top level in the component .
  • You can only use hooks inside the functional component .
  • You can call inside your custom hooks.

UseState() hook in React :

Whenever you will start to learn the hooks the first hook that comes to the picture is useState .

useState as the name suggest is used to manage the state in a functional component . It does the same work as state in a class based component .

Why to use useState hook:

If you are using the functional component and wants to use state inside the functional component then useState() comes into the picture .

syntax :

const [state , setState]=useState(initialvalueofstate);

for example :

const [count , setCount] = useState();
  • useState() return a pair of values , first is the current state and other is functional to update the that state .

In the example above the setCount will be used to update the count variable.

Till now we talked about the useState hooks , its use and syntax .

Now how to use read the state .

So if you wants to read the value then in class based component we do something like this

<h2> the count is {this.state.count}</h2>

In functional component with useState you can directly access the value like this

<h2>the Count is {count} </h2>

Updating the state :

From our previous knowledge we know that useState returns function to update a state . So code looks like this

function updateCount ()
    setCount(count + 1);

we can also update something like this .

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

  • Example above shows that we don't need to create function everytime to update the state.
  • count in the above return the current count value and on click of button it updates the value of count.

So that's it for useState hook . If you like it or find it useful. Please give it a heart and please leave your suggestions in the comments below . See you later in the useEffect.