React `useState` Hook: Managing State in Functional Components

Master state management in React functional components using the `useState` Hook. This tutorial explains its functionality, demonstrates its use with various data types, and shows how to update state values efficiently, simplifying component development and improving code readability.



Understanding and Using the React useState Hook

Introduction to the useState Hook

The useState Hook is a React feature (available from React 16.8 onwards) that lets you add state to functional components. Before Hooks, only class components could manage state. useState simplifies state management, making functional components more powerful and easier to work with.

How useState Works

useState is a function that takes an initial state value as an argument and returns an array containing two items:

  1. The current state value.
  2. A function to update that state value.
useState Syntax

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

You can use a function to calculate the initial state if needed:

useState with Function for Initial State

const [sum, setSum] = useState(() => 8 + 7);

Using useState

  1. Import useState: import { useState } from 'react';
  2. Call useState: Call it within your functional component. It returns the current state and an update function.
  3. Update State: Use the update function (the second value returned by `useState`) to change the state value. You cannot directly assign a new value to the state variable.
Basic useState Example

const MyComponent = () => {
  const [counter, setCounter] = useState(0);
  const handleClick = () => setCounter(counter + 1);
  return (
    <div>
      Counter: {counter}
      <button onClick={handleClick}>Increase</button>
    </div>
  );
};

Data Types Supported by useState

useState can handle various data types:

  • Strings
  • Numbers
  • Booleans
  • Arrays
  • Objects

Updating Objects in State

To update only a portion of an object in state, use the spread operator to create a new object with the desired changes:

Updating Object State

setCar(prevState => ({ ...prevState, color: 'blue' }));

Multiple useState Calls

You can use multiple calls to useState within a single component to manage multiple state variables independently.

useState vs. setState in Class Components

The `useState` hook serves the same purpose as `setState()` in class components but in a simpler, more functional way. It's only available in functional components.

Next Topic: [Next Topic Title]


Remember to replace `[Next Topic Title]` with the actual title of your next section.