DEV Community

Keertivaas S
Keertivaas S

Posted on

useState and useReducer

Similarities between useState and useReducer:

Both useState and useReducer are React hooks used for managing state in functional components. They share these key points:

  • State Management: They both allow you to store and update data within a component that can trigger re-renders when the state changes.

  • Functional Components: They are exclusive to functional components in React, providing an alternative to the setState method in class components.

  • Return Value: Both hooks return an array containing:

    • The current state value.
    • A function to update the state (setter function for useState and dispatch function for useReducer).

When to use useState:

  • Simple State: It's ideal for managing a single piece of state, especially primitive values (strings, numbers, booleans) or single objects/arrays.
  • Straightforward Updates: The state updates are easy to understand and don't require complex logic or dependencies on previous state values.
  • Readability: You prioritize keeping your component code concise and easy to reason about.

When to use useReducer:

  • Complex State Management: You're dealing with multiple state values that are updated interdependently or require handling previous state values.
  • Centralized Logic: You want to centralize state update logic in a separate reducer function to improve code maintainability and reusability.
  • Advanced Patterns: You need to implement advanced state management patterns like state history or optimistic updates.
  • Performance Optimization (Deep Updates): You're working with deep updates in the component tree, where useReducer can offer slight performance improvements because dispatch functions can be passed down without recreating functions on every render.

Top comments (3)

Collapse
 
brense profile image
Rense Bakker

Use reducer whenever your component state is an object. Handling updating object properties is just way easier with a simple reducer function:

function simpleReducer(currentState, newState){
  return {...currentState, ...newState}
}

const initialState = {
  name: '',
  email: ''
}

function SomeComponent(){
  const [person, setPerson] = useReducer(simpleReducer, initialState)
  return <button onClick={() => setPerson({ name: 'hello' })}>click</button>
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rgolawski profile image
Rafał Goławski

99% of cases when I'm working on an application I stick to useState, but not gonna lie, there is something satisfying about moving state update logic from event handlers into a reducer outside component. 😅

Collapse
 
mfp22 profile image
Mike Pearson

Yeah it's called declarative coding :)
It's good that you're comfortable switching early rather than later. dev.to/this-is-learning/how-to-not...