Aeria Leeve Says

React.useReducer

The problem with React.useState is that it makes you falling into the trap of creating new function on each render.

Take the following counter app for example, everytime when Home is re-rendered, the arrow function around setCounter is re-created.

This is no good.

import {useState} from "react";

export default function Home() {
  const [counter, setCounter] = useState(0);
  return (
    <button onClick={() => { setCounter(counter + 1) }}>+1</button>
  )
}

We can easily fix this with React.useReducer.

Voila! No function is re-created on re-render.

import {useReducer} from "react";

const counterReducer = (counter) => counter + 1;

export default function Home() {
  const [counter, dispatch] = useReducer(counterReducer, 0);
  return (
    <button onClick={dispatch}>{counter}</button>
  )
}