DEV Community

Discussion on: 2 use cases of the useReducer ReactJS hook

Collapse
 
icyjoseph profile image
Joseph • Edited

I don't really like the syntax used in Manage multiple states, but I guess it works.

One case to consider is that of batching, and how it is not consistent up to React 17.

This handler for example:

 const handler = () => {
    fetch("https://pokeapi.co/api/v2/pokemon/pikachu").then(() => {
      setData(() => {
        return { name: "Joe" };
      });

      setLoading(() => {
        return "Done";
      });
    });
  };
Enter fullscreen mode Exit fullscreen mode

Triggers two, albeit very quick, renders. React 18 will fix this, but in the mean time, useReducer does the trick.

Checkout this CodeSandBox, notice that the useState trigger logs two render counts per click, while the useReducer example logs one render count.

Collapse
 
colocodes profile image
Damian Demasi

Very interesting... Thanks!