dai-shi / react-tracked

State usage tracking with Proxies. Optimize re-renders for useState/useReducer, React Redux, Zustand and others.
https://react-tracked.js.org
MIT License
2.74k stars 72 forks source link

[Question] Why does re-rendering occur even when using React.memo? #226

Open sangsang-6914 opened 3 hours ago

sangsang-6914 commented 3 hours ago

hello, dai-shi! While studying your book, “Micro State Management with React Hooks,” I encountered an issue. In the example below, when count changes, only the Counter component should re-render. However, it seems that the re-render optimization is not working as expected.

Issue Code

import { memo, useState } from "react";
import { createContainer } from "react-tracked";

const useValue = () => useState({ count: 0, text: "hello" });

const { Provider, useTracked } = createContainer(useValue);

const Counter = memo(() => {
    const [state, setState] = useTracked();
    const inc = () => {
        setState((prev) => ({ ...prev, count: prev.count + 1 }));
    };
    return (
        <div>
            count: {state.count} <button onClick={inc}>+1</button>
        </div>
    );
});

const TextBox = memo(() => {
    const [state, setState] = useTracked();
    const setText = (text: string) => {
        setState((prev) => ({ ...prev, text }));
    };
    return (
        <div>
            <input value={state.text} onChange={(e) => setText(e.target.value)} />
        </div>
    );
});

const App = () => (
    <Provider>
        <div>
            <Counter />
            <Counter />
            <TextBox />
            <TextBox />
        </div>
    </Provider>
);

export default App;

Even when the count changes, the TextBox component is re-rendering, and I can’t figure out why. I confirmed that re-rendering is occurring by using the “Highlight updates when components render.” feature in Chrome React DevTools.

simjieun commented 3 hours ago

I am experiencing the same issue as well.