Skip to main content

State Management

State allows components to manage their internal data that can change over time. This dynamic data drives the component's behavior and appearance, leading to interactive and responsive user interfaces.

Why Use State?

  • Dynamic Updates: When state changes, React automatically re-renders the component, reflecting the updated data in the UI.
  • Component-Specific Data: State is private to each component, encapsulating data relevant to its functionality.
  • Interactive UIs: By managing state changes based on user interactions or external events, you can create dynamic and engaging user experiences.

State in Functional Components with Hooks

While traditionally associated with class components, the introduction of Hooks in React 16.8 has revolutionized state management in functional components. The useState Hook is the primary tool for managing state in functional components:

import { useState } from 'react';

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

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

return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}

In this example:

  • We import useState from react.
  • The useState Hook is used to create a state variable count with an initial value of 0 and a setter function setCount.
  • The handleClick function increments the count state using setCount.
  • The component displays the current count and a button that triggers the re-render with the updated state.

Additional Hooks for State Management

Beyond useState, React offers other Hooks for complex state management scenarios:

  • useEffect: Used for side effects, data fetching, and subscriptions that may affect component state.
  • useReducer: For managing complex state with a reducer function, often used with larger applications.
  • useContext: Provides a way to share state across non-parent-child component relationships using a React Context.

You will learn about these hooks later in the series.