Learning on Web Dev Open is free for all.

Framework Internals > Effects, and the ones you should deleteWhat an effect is actually for
Phase 04Effects, and the ones you should delete204 of 434

What an effect is actually for

Synchronising your component with a system that does not know it exists. That is the entire job description.

Concept13 minAI pair

The document title. A WebSocket. A map widget from a library that manipulates its own DOM. An analytics call. A media query listener. Local storage. These are external systems: things that exist outside the render, that will not update themselves when your state changes, and that need to be told and then untold.

That is the test. If the effect is synchronising with something outside, it belongs. If it is reacting to a prop change by setting state, transforming data, or triggering the next step of a flow, it is doing control flow in the wrong place and there is a better position for that code, during render, in the event handler, or at the top of the component.

The mental model that helps is that an effect describes a state, not an action. It says "while this component is mounted with these values, this external thing should be set up like so". The cleanup is not an afterthought, it is the other half of the sentence, and an effect where the cleanup is hard to write is usually an effect that should be an event handler.

You should now be able to

  • State the one thing effects are for
  • Recognise an external system when you see one
Ask the community

Loading…