Menu

gitpiper

useEffectOnce react Code Snippet in 2024

hookseffectbeginner

Last Updated: 20 April 2024

Runs a callback at most once when a condition becomes true.

  • Use the useRef() hook to create a variable, hasRunOnce, to keep track of the execution status of the effect.
  • Use the useEffect() that runs only when the when condition changes.
  • Check if when is true and the effect has not executed before. If both are true, run callback and set hasRunOnce to true.
const useEffectOnce = (callback, when) => { const hasRunOnce = React.useRef(false); React.useEffect(() => { if (when && !hasRunOnce.current) { callback(); hasRunOnce.current = true; } }, [when]); };
const App = () => { const [clicked, setClicked] = React.useState(false); useEffectOnce(() => { console.log('mounted'); }, clicked); return <button onClick={() => setClicked(true)}>Click me</button>; }; ReactDOM.render(<App />, document.getElementById('root'));

react snippet similar to useEffectOnce For You in April 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️