react-hooks: skip first run in useEffect

seyed picture seyed · Nov 17, 2018 · Viewed 20.5k times · Source

How I can skip first run in useEffect hook.

useEffect(() => {
    const first = // ???
  if (first) {
    // skip
  } else {
    // run main code
  }
}, [id]);

Answer

Tholle picture Tholle · Nov 17, 2018

The useRef hook can be used to store any mutable value, so you could store a boolean indicating if it's the first time the effect is being run.

Example

const { useState, useRef, useEffect } = React;

function MyComponent() {
  const [count, setCount] = useState(0);

  const isFirstRun = useRef(true);
  useEffect (() => {
    if (isFirstRun.current) {
      isFirstRun.current = false;
      return;
    }

    console.log("Effect was run");
  });

  return (
    <div>
      <p>Clicked {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

ReactDOM.render(
  <MyComponent/>,
  document.getElementById("app")
);
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="app"></div>