MiddleReact

When does useEffect run in React? What is the dependency array for?

useEffect runs after React has updated the screen. It's for keeping a component in sync with something outside React: calling an API, subscribing to events, setting timers.

  • No dependency array: it runs after every render.
  • An empty array []: it runs once, after the first render.
  • With values such as [id]: it runs again whenever id changes.

The function returned from the effect is the cleanup function. It runs before the next effect and when the component is removed, for example to clear a timer or remove an event listener.