Sventies
Sventies

Reputation: 2766

Prevent rerenders with react hooks

I'm implementing zustand for global state, but I ran into the same issue when setting up my own global state.

As soon as I attach a component to a simple useStore hook, my component renders twice for every update. This happens despite:

Here's a Codesandbox - a minimal example where you can check the logs - after a reload and after every update, it always logs twice. For people who rather see code without it running:

import React from "react";
import create from "zustand";

const useStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 })
}));

const sessionId = Math.random().toString().slice(2, 7);

const App = React.memo(() => {
  const { bears, increasePopulation } = useStore((state) => state);

  console.log("RENDER Bears", bears, sessionId); // always logs twice
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen.!</h2>
      <button onClick={increasePopulation}>increase</button>
    </div>
  );
});

export default App;

Now, I understand that having one extra render is not really a problem, it's just that when my app grows, I tend to have a couple of those components nested into each other, so that when I do want to minimise the amount of renders, it becomes hard to know where to start.

So, my questions are:

Upvotes: 1

Views: 1217

Answers (1)

knada
knada

Reputation: 344

This is probably because your app is wrapped in React.StrictMode. The react core team says the double render is intentional.

It's an intentional feature of the StrictMode. This only happens in development, and helps find accidental side effects put into the render phase. We only do this for components with Hooks because those are more likely to accidentally have side effects in the wrong place.

https://github.com/facebook/react/issues/15074

Upvotes: 1

Related Questions