useState vs useReducer - choose your champion 🤺
Clara Situma

Clara Situma @csituma

About: i love technology I love simplifying complex topics.,and solving problems

Location:
Nairobi
Joined:
Sep 25, 2020

useState vs useReducer - choose your champion 🤺

Publish Date: Dec 16 '22
5 1

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?

Comments 1 total

  • 205th
    205thDec 18, 2022

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

Add comment