How to Use React Hooks for State Management: A Practical Tutorial

React Hooks let you manage state in functional components without writing a class. They simplify code, reduce boilerplate, and make state logic reusable. This tutorial covers the three most common hooks for state management: useState, useReducer, and useContext.

Before diving in, remember that hooks must be called at the top level of your component, not inside conditions or loops. Now let’s explore each hook with a simple example.

Article illustration

1. useState for Local State

useState is the simplest hook for managing a single piece of state. It returns an array with the current state and a setter function.

  • Example: const [count, setCount] = useState(0);
  • Use it for: toggles, form inputs, UI flags.

To update, call setCount(count + 1). For objects or arrays, always spread the previous state to avoid mutations.

2. useReducer for Complex State

When state logic gets complex—like multiple sub-values or transitions—useReducer shines. It works like a mini-Redux inside a component.

  • Example: const [state, dispatch] = useReducer(reducer, initialState);
  • Use it for: shopping carts, multi-step forms, undo/redo.

Define a reducer function that takes the current state and an action, then returns the new state. Dispatch actions with dispatch({ type: 'INCREMENT' }).

3. useContext for Global State

To share state across many components without prop drilling, combine useContext with the Context API.

  • Example: Create a context with React.createContext(), wrap your app in a Provider, and consume with useContext(MyContext).
  • Use it for: themes, user authentication, language settings.

For frequent updates, consider pairing useReducer with useContext for a lightweight global state solution.

Conclusion

React Hooks give you fine-grained control over state without classes. Start with useState for simple needs, upgrade to useReducer for complex logic, and use useContext to pass state globally. Each hook is composable—build custom hooks to reuse state logic across your app.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *