React useEffect only on Update

 by Robin Wieruch
 - Edit this Post

If you are wondering how to run React's useEffect Hook only on update, you may be surprised that you need for tracking the component's lifecycle. The following code shows you how to achieve it:

import * as React from 'react';
const App = () => {
const [toggle, setToggle] = React.useState(true);
const handleToggle = () => {
setToggle(!toggle);
};
const didMount = React.useRef(false);
React.useEffect(() => {
if (didMount.current) {
console.log('I run only if toggle changes.');
} else {
didMount.current = true;
}
}, [toggle]);
return (
<div>
<button type="button" onClick={handleToggle}>
Toggle
</button>
{toggle && <div>Hello React</div>}
</div>
);
};
export default App;

If you want to have a reusable custom hook for it, which only triggers the effect function only on update (and not on mount), you can use the following hook for it:

import * as React from 'react';
const useEffectOnlyOnUpdate = (callback, dependencies) => {
const didMount = React.useRef(false);
React.useEffect(() => {
if (didMount.current) {
callback(dependencies);
} else {
didMount.current = true;
}
}, [callback, dependencies]);
};
const App = () => {
const [toggle, setToggle] = React.useState(true);
const handleToggle = () => {
setToggle(!toggle);
};
useEffectOnlyOnUpdate((dependencies) => {
console.log('I run only if toggle changes.');
}, [toggle]);
return (
<div>
<button type="button" onClick={handleToggle}>
Toggle
</button>
{toggle && <div>Hello React</div>}
</div>
);
};
export default App;

That's it. React's useEffect Hook doesn't come with a feature to run it only on update, however, this custom hook should help you to accomplish it. Let me know if this helps you.

Keep reading about 

If you are wondering how to run React's useEffect Hook only once , you may be surprised that you need React's useRef Hook as helper to create an instance variable for tracking the component's…

In this tutorial you will learn everything about React's useEffect Hook. Let's say we have these two components whereas the parent component manages state with React's useState Hook and its child…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.