DEV Community

Clara Situma
Clara Situma

Posted on

2

useState vs useReducer - choose your champion 🤺

Below are two ways of implementing a simple counter in a React application:

Here's how to achieve that with useReducer:

import { useReducer } from 'react';

const initialState = {
  count: 0,
};

const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      return state;
  }
};

function ParentComponent() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>Count: {state.count}</p>
      <ChildComponent dispatch={dispatch} />
    </div>
  );
}

function ChildComponent(props) {
  return (
    <div>
      <button onClick={() => props.dispatch({ type: "increment" })}>
        Increment
      </button>
      <button onClick={() => props.dispatch({ type: "decrement" })}>
        Decrement
      </button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Here's how to achieve that using useState

import { useState } from 'react';

function ParentComponent() {
  const [state, setState] = useState({ count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <ChildComponent setState={setState} />
    </div>
  );
}

function ChildComponent(props) {
  return (
    <div>
      <button onClick={() => props.setState({ count: props.count + 1 })}>
        Increment
      </button>
      <button onClick={() => props.setState({ count: props.count - 1 })}>
        Decrement
      </button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Which one are you picking and why?

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (1)

Collapse
 
205th profile image
205th

useState for local, useReducer for global, plus to avoid props drilling

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay