Skip to content

Instantly share code, notes, and snippets.

@nikparo
Created February 18, 2021 09:04
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikparo/33544fe0228dd5aa6f0de8d03e96c378 to your computer and use it in GitHub Desktop.
Save nikparo/33544fe0228dd5aa6f0de8d03e96c378 to your computer and use it in GitHub Desktop.
Running React parent effects before child effects
// Sometimes you want to run parent effects before those of the children. E.g. when setting
// something up or binding document event listeners. By passing the effect to the first child it
// will run before any effects by later children.
export function Effect({ effect }) {
useEffect(() => effect?.(), [effect]);
return null;
}
//
// Use it like this:
//
function Parent() {
const stableEffect = useCallback(() => doStuff(), []);
return (
<>
<Effect effect={stableEffect} />
<SomeChild />
</>
);
}
@talkohavy
Copy link

You deserve a medal for this solution! Thank you for inventing it for us :)

@scjonatas
Copy link

You saved my life! Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment