react-hooks: skip first run in useEffect

ReactjsReact Hooks

Reactjs Problem Overview


How I can skip first run in useEffect hook.

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

Reactjs Solutions


Solution 1 - Reactjs

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionseyedView Question on Stackoverflow
Solution 1 - ReactjsTholleView Answer on Stackoverflow