Back to Curriculum

State and Hooks (useState)

📚 Lesson 3 of 18 ⏱️ 50 min

State and Hooks (useState)

50 min

State is data that a component maintains. When a component's state changes, React re-renders the component.

The `useState` hook is a function that lets you add React state to function components.

It returns a pair: the current state value and a function that lets you update it.

State updates are asynchronous and batched for performance. React may batch multiple setState calls into a single re-render.

The initial state value is only used on the first render. Subsequent renders use the current state value.

You can pass a function to setState to update based on the previous state, which is important for avoiding stale closures.

Key Concepts

  • useState hook enables state management in functional components.
  • State updates trigger component re-renders automatically.
  • State updates are asynchronous and may be batched by React.
  • Use functional updates when new state depends on previous state.
  • Each component instance has its own independent state.

Learning Objectives

Master

  • Using useState hook to manage component state
  • Understanding when and how React re-renders components
  • Using functional updates for state that depends on previous values
  • Initializing state with values and functions

Develop

  • State management thinking and data flow understanding
  • Recognizing when state updates are needed
  • Understanding React's rendering cycle

Tips

  • Use functional updates (setCount(prev => prev + 1)) when state depends on previous value.
  • Initialize state with a function if the initial value is expensive to compute.
  • Keep state as local as possible - lift it up only when necessary.
  • Use multiple useState calls for unrelated state values.

Common Pitfalls

  • Mutating state directly instead of using the setter function.
  • Using stale state values in closures without functional updates.
  • Creating too many state variables - consider useReducer for complex state.
  • Forgetting that state updates are asynchronous.

Summary

  • useState hook manages local component state in functional components.
  • State changes trigger automatic re-renders.
  • Use functional updates when new state depends on previous state.
  • Each component instance maintains its own state independently.

Exercise

Create a counter component with a button that increments a number.

import { 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>
  );
}

Exercise Tips

  • Use functional update: setCount(prev => prev + 1) for better practice.
  • Consider adding a reset button to set count back to 0.
  • Add input validation if allowing manual count entry.
  • Test with React DevTools to see state changes in real-time.

Code Editor

Output