Home > other >  why child re-render even if I have used useCallback
why child re-render even if I have used useCallback

Time:11-09

const Root = () => {
  /** useState */
  const [count, setCount] = useState(1);
  const [times, setTimes] = useState(1);

  const handleCount = useCallback(() => {
    setCount(count * 2);
  }, []);

  const handleTimes = useCallback(() => {
    setTimes(times   2);
  }, []);

  return (
    <div>
      <div>Root. counts: {count}</div>
      <Counter onClick={handleCount} value={count} />
      <Counter onClick={handleTimes} value={times} />
    </div>
  );
};

child-component will re-render when parent-component re-render, so I don't know why I should use useCallback, in which case will function(in useCallbak) change but my componet won't re-render, because when function change, it shoule be component's state change, state change will cause re-render, so my useCallbak is not working at all(not prevent re-render)

CodePudding user response:

First, you haven't defined a dependency array for either of your useCallbacks. The child components would rerender if the function were rebuilt, or if the value were to change. Use should also be using the lazy set method of state.

const handleCount = useCallback(() => {
  setCount(prev => prev * 2);
}, [setCount]);

CodePudding user response:

I suggest you to use React.memo in your child component.

This code will help you,

export const Counter = React.memo(props => {
    return ...
})

Here is the doc link.

  • Related