What is the use of 'useState' hook in React?

Understanding the 'useState' Hook in React

React's useState is a built-in hook that allows you to add state functionality to functional components. Prior to the introduction of hooks in React 16.8, class components were primarily used for state management. However, with the advent of hooks, state and other React features can now be leveraged in functional components, leading to cleaner, more readable code.

How Does 'useState' Work?

useState is a function that takes the initial state as a parameter and returns an array that has two values:

  • The current state value
  • A function that can update this state value

Here is a sample syntax of using useState:

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

In the above code:

  • state represents the current state value which is initialized to initialState.
  • setState is a function to update the state value.

It's important to note that useState doesn't merge the old and new state like this.setState in class components. Instead, it replaces the old state. Therefore, you have to manually include the old state when updating if necessary.

Practical Example: A Counter Application

A simple and practical example of useState usage is in a counter application. In this scenario, the state holds the current count value, and setState changes the count value:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Counter;

In this example, the count starts at 0 (useState(0)). When the button is clicked, setCount is invoked with the new count (count + 1), updating the state, and consequently, the component re-renders.

Best Practices

Here are a few best practices when using useState:

  1. Define multiple state variables when dealing with complex state logic; useState can be used more than once in a single component.
  2. When updating state based on the previous state, use the functional form of setState like setCount(prevCount => prevCount + 1). This ensures that you always have the latest state value.
  3. Avoid calling Hooks inside loops, conditions, or nested functions to preserve the order of Hooks calls between component re-renders.

By understanding the 'useState' hook in React, you can better manage state in functional components, leading to optimized, modular, and easily testable code.

Do you find this helpful?