0

I'm following this tutorial

https://javascript.plainenglish.io/5-advanced-react-patterns-a6b7624267a6

Can you explain me what's the purpose of this code, please?

const firstMounded = useRef(true);
  useEffect(() => {
    if (!firstMounded.current) {
      onChange && onChange(count);
    }
    firstMounded.current = false;
  }, [count, onChange]);

https://github.com/alex83130/advanced-react-patterns/blob/main/src/patterns/compound-component/Counter.js#L9

user3887366
  • 2,226
  • 4
  • 28
  • 41
  • 3
    It's to call your `onChange()` function only when `count` is updated. Without the ref / condition, `onChange()` would be called upon mounting as well (see [Make React useEffect hook not run on initial render](https://stackoverflow.com/q/53253940)) – Nick Parsons May 23 '21 at 09:35
  • https://stackoverflow.com/questions/59492626/stop-useeffect-from-running-on-mount/59492738#59492738 – Dennis Vash May 23 '21 at 09:35

1 Answers1

1

useEffect is react renders after a component is mounted / rendered in the DOM . In your case , the useEffect will be triggered,

  1. when the component is mounted for the first time
  2. when the value of count changes
  3. when the onChange changes ,
Shyam
  • 5,292
  • 1
  • 10
  • 20