React Hook to Run Code After Render

By Dave Ceddia

Need to run some code after a React component renders?

Maybe you’re familiar with componentDidUpdate and you’re looking for the equivalent hook…

Well look no further… the answer is the useEffect hook.

The After-Render Hook: useEffect

The useEffect hook is used like this:

function MyComponent() {
  useEffect(() => {
    // code to run after render goes here
  });

  return (
    <div>whatever</div>
  );
}

This will run the effect after every render – the same as componentDidUpdate in class components.

useEffect Can Run Less Often

By default, the effect will run every time the component re-renders, but you can limit it down to run when you want.

Run Code Once

If you want something more like componentDidMount, that is, code that’ll run one time after the initial render, after the component is mounted, you can call useEffect like this:

function MyComponent() {
  useEffect(() => {
    // code to run after render goes here
  }, []); // <-- empty array means 'run once'

  return (
    <div>whatever</div>
  );
}

Pass an empty array as the second argument to useEffect and it will only run once, after the first render.

Without the right mental model, useEffect is super confusing.
With the right mental model, you'll sidestep the infinite loops and dependency warnings before they happen.
Get great at useEffect this afternoon with Learn useEffect Over Lunch.

Can you run a hook before render?

The short answer is no, not really. useEffect is the only hook that is meant for tying in to the component lifecycle, and it only ever runs after render. (useLayoutEffect is the same, it also runs after render).

The longer answer is that technically, a React hook is just a function. And you could write a custom hook that’ll run before the component returns – just call it like you would any other function.

Don’t do this, though: React can and will sometimes call your components multiple times before actually rendering them to the screen, so you can’t rely on “one call == one render”.

The real answer is that trying to run code before a component renders usually is a misunderstanding of how React works. There is no “before”. There is only “after”.

Re-think your approach so that it can work with an intermediate state, where the component renders at least once in an “un-ready” state. If you want to wait for data to load, for instance – check if the data is ready, and if not, return early. Or, ensure that your component will survive missing data, by initializing your state to an empty array or some other “empty” value (rather than null or undefined).

If you absolutely need to run code before something renders, do it in the parent, and conditionally render the child once whatever you need is “ready”.

Also, check out the cheatsheet I put together (below) for 5 examples of useEffect and the equivalent lifecycle methods.