What is useState() hook in ReactJs?

React hooks are the new feature added in the React 16.8 version. In the previous versions, the class-based components were the only way to manipulate the state. If we had a functional-based component and we wanted to manage the state from it then we would have to convert our component to class-based. So to make this convenient, useState() hook is used.

How to use the useState() hook in ReactJs?

At first, we will import the useState() hook from React inside the functional component, which is Example.js in our case. Below is the code where we create two state variables – like and dislike, for instance.

import React,{useState} from "react";
const Example = () => {
    const [like,setLike]=useState(0);
    const [dislike,setDislike]=useState(0);
    return (
        <div>
            
        </div>
    )
}
export default Example;

useState hook takes only one parameter which determines the initial value of the state variable, that is 0 in this case.

This hook returns two values-

  1. the current state (like and dislike)
  2. the function that will update that state. (setLike and setDislike)

The [ ] bracket is necessary as it assigns the first return value to the state variable and the second return value to function. This is also known as Array Destructuring.

Now let’s use these state variables.

import React,{useState} from "react";
const Example = () => {
    const [like,setLike]=useState(0);
    const [dislike,setDislike]=useState(0);
    return (
        <div>
            <button onClick={()=>setLike(like+1)}>Like {like}</button>
            <button onClick={()=>setDislike(dislike+1)}>Dislike {dislike}</button>
        </div>
    )
}
export default Example;

We are using the setLike and setDislike function to increment the value of the like and dislike variable respectively on clicking the buttons. For this, we are using the onClick event.

The output would look like this:

After clicking, it would look like this:

Note:

  • Hooks don’t work inside classes.
  • The state variables created using hooks don’t have to be an object as they are in the case of classes.
  • We can only call hooks from react functions and not from regular JavaScript functions.
  • Hooks should not be called inside loops.

Conclusion:

This was all about useState() hook in React Js. You just need to have React of version 16.8 or above, node version 6 or above, and npm version 5.2 or above. Then you are good to go. You can go through the official documentation of React hooks for more examples.

Leave a Reply

Your email address will not be published. Required fields are marked *