The way to check if it’s the first time for useEffect function is being run in React Hooks

Anna Coding
Anna Coding
Published in
2 min readJan 16, 2020

We use the useEffect() hook to simulate componentDidMount and componentDidUpdate, but it seems like useEffect() is being ran after every render, even the first time.

🤔So the question is how do we prevent it to run on initial render for some cases?

💡We can use useRef hook to solve this issue.

useRef hook can store any mutable value we want, so we could use that to keep track of if it’s the first time the useEffect function is being run. See below codes snippet.

const { useState, useRef, useEffect } = React;

const ExampleFunction = (value) => {
const firstUpdate = useRef(true);

useEffect(() => {
if (firstUpdate.current) {
firstUpdate.current = false;
return;
}
console.log("Not the first update");
// Do something
});

return (
<div>
{ value }
</div>
);
}

--

--

Anna Coding
Anna Coding

Free web, mobile, DevOps, cloud tutorials, issues & solutions. www.annacoding.com