What is 'useState' in React?

useState is a hook in React. Hooks were introduced in React so that you can use state and lifecycle methods in functional components.

Let's say you want a simple like counter app.

import React from 'react';

const App = () => {
    let counter = 0;

    const btnClickHandler = () => {
        counter += 1;
        console.log(counter);
    };
    return (
        <div>
            <h1>Like Counter</h1>
            <h3>{counter}</h3>
            <button type="button" onClick={btnClickHandler}>
                Click
            </button>
        </div>
    );
};

export default App;

Now what happens if you click the button?

react-without-usestate.png

As you can see in the console the value of counter does change but react will not rerender the counter value on your screen. This is where the useState hook comes in. useState hook is a function that lets you add React state to functional components. To use, simply write a named import

import React, { useState } from 'react';

useState is a function which returns an array with two elements. The first element is the state value we are going to use and the second one is a function to control the state value. These return values are used by using the array destructuring method.

const [counter, setCounter] = useState(0);

The left hand side of this syntax refers to the variable names of the return values of useState function. On the right side we invoke the useState function because we want the returned array for destructuring. This invoked function will take the default state value of state which can be either a string, number, boolean, array, object, even null.

Now in this example counter will refer to the variable name for the state value and setCounter will refer to the function which will control the state value. Now you can name these variables anything you want, even apples and bananas, but the common convention is to use the same variable name for the function, as the state value name, with prefix of set. Since it is a like counter the initial value is set as a Number 0.

Now to update the counter value just use

import React, { useState } from 'react';

const App = () => {
    const [counter, setCounter] = useState(0);

    const btnClickHandler = () => {
        setCounter(counter + 1);
    };

    return (
        <div>
            <h1>Like Counter</h1>
            <h3>{counter}</h3>
            <button type="button" onClick={btnClickHandler}>
                Click
            </button>
        </div>
    );
};

export default App;

react-usestate-example.png

Now everytime you click the button, the btnClickHandler function invokes the setCounter function which takes the previous counter value and increments it by 1.

Everytime you want to update the UI dynamically you will be using one of the React hooks. There are some general rules of hooks.

Some general rules of hooks

  1. Component name must start with uppercase. Notice the functional component App starts with a capital letter. Try changing it to a small letter. React will throw an error saying app is not a React functional component or custom hook. Hooks only be called from React functional components and from custom hooks.
  2. Hooks need to be invoked inside the function body and at the top level. By doing this you ensure that hooks are called in the same order each time a component renders.
  3. Hooks cannot be called conditionally. Everytime a component renders the hooks must be called in exact same order. You can use conditionals inside a hook but a hook cannot be called conditionally.

useState is the most basic and most used hook in React. It will always return an array with a initial value and a setter function to change the value.