How to use the useState() Hook in React

How to use the useState() Hook in React

ยท

4 min read

In my last article, I covered the rudiments of React Hooks and the problems they came to solve. In this article, I'll like us to take a detailed look at the useState hook. Before I continue if you haven't read the article on the fundamentals of React Hooks, you can give it a read here. Without any further long talk, let's begin.

What is the useState hook?

useState() is a React hook that allows you to have state variables in React's functional components. State simply refer to the data and properties that you use in your application. These states are mutable meaning their value can be changed. useState() is used to manage and handle states in a React application. It allows you to create, track and update a state in a functional component. This hook takes the initial state(value) as an argument and returns an array of two entries. The initial value could be of any data type. We will see what this means below so keep going. The useState() hook is an in-built React hook so you don't have to install it when you create a new React project.

To use this hook, you ought to do the following:

  1. You must first import it from React, or you will have to invoke it like React.useState() anytime you have to create a state.

  2. You must invoke it inside a functional component.

Let's see how this is done with some code.

import React, { useState } from 'react';

 const [count, setCount] = useState({ number: 5 });
    return (
        <div>
            <p>{count.number}</p>
        </div>
    );
};

For those who don't quite get what is happening with the array, it is called destructuring and you can get more insights about this amazing javascript feature from this article. It is important to know that the useState() hook does not return just a variable but it also returns a second value, a function that you can use to update the state value. So in the case of the code block above, setCount is the function that can be used to update the value of the count variable. You can call the function anything you want but it is good practice to use the variable name with a prefix of set .

Updating a state with useState()

An excellent way to see how the useState() hook is used in updating a state is if you have a number whose default value is say 0, and then you want this number to be incremented by 1 whenever a button is clicked. This means that when the button is clicked, you want your state to update by adding one to whatsoever number the current value is:

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

    const incrementCount = () => {
        setCount(count + 1);
    };

    return (
        <div>
            <p>{count}</p>
            <button type="button" onClick={incrementCount}>
                Increment Count
            </button>
        </div>
    );
};

In the code block above, count is the state variable, setCount is the function used to update the state, while 0 is the initial value.

The state value is displayed on the web page alongside a button with an onClick() event. In the click event, an increment function is passed, which we called and used the setCount function to increment the value of the count variable.

Rules to follow when using hooks

Hooks are JS functions but two major rules apply when using them. These rules are:

  1. Only call hooks at the top level of your component: What this means is within your component, you should only call hooks at the top and not inside any loops, conditions, or nested functions. This helps React preserve and call hooks in the same order each time a component renders.

  2. Only call hooks inside a functional component: Hooks were created for functional components and so should only be used inside functional components. They don't work in class components. If you have to use state in the class component, you will need to make use of the state object.

Conclusion

We have looked at the useState hook in detail in this article. I hope I was able to help you understand this hook. You can share you thoughts about this article with me in the comments section. Thank you for reading this article until next time, it's Goodbye!!