Search code examples
reactjsreact-usememo

React - useMemo giving warning although program is running fine. (useMemo has an unnecessary dependency)


First of all sorry for bad code. I am new to React, so please excuse me :P. Here I have created 2 buttons, "add" and "Change fake". When I click on "add" it will not re-render child component and when I click on "change fake", It does re-render the component because my dependency has changed in useMemo and it creates and sends a new object props to child. But I am getting a warning for useMemo saying it's an unnecessary dependency although I need to dependency. How can I go that warning go away. Is there a better way to do this?

Note: My child component is a dummy component. It does not do anything with those props.

import Child from "./Child";

const Parent = () => {
  const [count, setCount] = useState(0);
  const fakeValue = useRef(10);

  const randomProp = useMemo(() => {
    return { val: fakeValue.current };
  }, [fakeValue.current]);

  const changeFake = () => {
    fakeValue.current = fakeValue.current + 1;
    setCount(count + 1);
  };

  return (
    <>
      <div>{count}</div>
      <div>{fakeValue.current}</div>
      <button onClick={() => setCount(count + 1)}>add</button>
      <button onClick={() => changeFake()}>Change fake</button>
      <Child randomProp={randomProp} />
    </>
  );
};

export default Parent; 

Output link: https://i.sstatic.net/5spw1.png CodeSandbox link: https://codesandbox.io/s/silly-pine-fzjw9?file=/src/

Maybe a dumb question. But I would appreciate some feedback from the community please :)


Solution

  • When you pass fakeValue.current ref directly into dependency of useMemo it will not change value of randomProp. then child component wont re-render. So you need to do something like this.

    const randomValue = fakeValue.current;
    
      const randomProp = useMemo(() => {
        return { val: randomValue };
      }, [randomValue]);
    

    If re-render not required, just want to remove the warning, you can remove fakeValue.current dependency

    CodeSandbox link modified code : https://codesandbox.io/s/stoic-thunder-9ylxi?file=/src/Parent.js