Prevent an effect from firing at mount
Recently I have been encountering a lot of cases where I wanted to have an effect fire when a variable changes, but not when the component mounts, similar to how componentDidUpdate
behaves. I created this handy helper hook which I’ve since used in a lot of places:
import React from "react";
// A useEffect that doesn't fire at the first render
export const useSubsequentEffect = (fn, deps) => {
const isMountedRef = React.useRef(false);
React.useEffect(() => {
if (!isMountedRef.current) {
isMountedRef.current = true;
return;
}
return fn();
}, deps);
};
Use it as you would normally use an effect.
No AI tooling was used in the creation of this article. More articles: