React useEffectOnce hook

React, Hooks, Effect · Nov 16, 2021

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) {
      hasRunOnce.current = true;
  }, [when]);
const App = () => {
  const [clicked, setClicked] = React.useState(false);
  useEffectOnce(() => {
  }, clicked);
  return <button onClick={() => setClicked(true)}>Click me</button>;

ReactDOM.render(<App />, document.getElementById('root'));

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this