open-amdocs / webrix

Powerful building blocks for React-based web applications
https://webrix.amdocs.com
Apache License 2.0
431 stars 31 forks source link

Feature: React custom hook - useDepEffect #117

Open yairEO opened 1 year ago

yairEO commented 1 year ago

useDepEffect (use dependency effect)

Runs a useEffect only when the dependency array changes and not on initial mount. (see related stackoverflow discussion)

Instead of manually using a ref to know when the component mounted:

const isMountedRef = useRef();

useEffect(() => {
  if (isMountedRef.current)
    document.title = `You clicked ${count} times`;

  isMountedRef = true;
}, [count]); 

Use the custom hook (much shorter):

useDepEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes