Executes a callback immediately after a component is updated.
useRef()
hook to create a variable, mounted
, that tracks if the component has been mounted.useEffect()
hook to set the value of mounted
to true
the first time the hook is executed.callback
on subsequent hook executions.condition
, will only execute the hook if any of the dependencies change.componentDidUpdate()
lifecycle method of class components.const useComponentDidUpdate = (callback, condition) => {
const mounted = React.useRef(false);
React.useEffect(() => {
if (mounted.current) callback();
else mounted.current = true;
}, condition);
};
const App = () => {
const [value, setValue] = React.useState(0);
const [otherValue, setOtherValue] = React.useState(1);
useComponentDidUpdate(() => {
console.log(`Current value is ${value}.`);
}, [value]);
return (
<>
<p>
Value: {value}, other value: {otherValue}
</p>
<button onClick={() => setValue(value + 1)}>Increment value</button>
<button onClick={() => setOtherValue(otherValue + 1)}>
Increment other value
</button>
</>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
Would you like to help us improve 30 seconds of code?Take a quick survey
React, Hooks
Executes a callback immediately after a component is mounted.
React, Hooks
Executes a callback immediately before a component is unmounted and destroyed.
React, Hooks
Executes a callback whenever an event occurs on the global object.