Sometimes you need to know "is this the mount, or a re-render?" — to skip a validation on the initial paint, avoid firing an analytics event before the user has done anything, or run an animation only after the first frame. useIsFirstRender answers that in one boolean: true on the very first render of a component, false on every render after.
Implement useIsFirstRender(). It takes no arguments and returns a boolean. The flip from true to false must happen during render — no extra re-render, no waiting for an effect — and once it's false it stays false for the life of the component.
function useIsFirstRender() {
// returns true on the first render, false afterwards
}
function Search({ query }) {
const isFirst = useIsFirstRender();
useEffect(() => {
if (isFirst) return; // skip the fetch on mount
runSearch(query);
}, [query]);
}
const isFirst = useIsFirstRender();
// render 1 -> true
// render 2 -> false
// render 3 -> false
true and the second already sees false.true. Once false, always false.