Knowledgebase

Effects and Side Effects Print

  • frontenddevelopment, frontend, caching, guide, howto, solution, zillionkinghost, hosting
  • 0

Work outside rendering.

WHAT AN EFFECT IS FOR

Synchronising with something outside React: a subscription, a timer, a browser API.

WHAT IT IS NOT FOR

Transforming data for rendering Responding to user events Anything that could be computed during rendering

WHY THAT MATTERS

Effects used for those purposes produce extra renders and subtle bugs.

WHAT TO DO INSTEAD FOR EVENTS

Handle them in the event handler.

WHAT THE DEPENDENCY LIST DOES

Determines when the effect runs again.

WHAT GOES WRONG

Omitting dependencies, producing stale values Including values that change every render, producing infinite loops

WHAT TO DO ABOUT THE SECOND

Establish why the value changes each render, rather than removing it from the list.

WHAT CLEANUP IS FOR

Undoing what the effect did: removing listeners, cancelling requests, clearing timers.

WHY IT MATTERS

Without it, subscriptions accumulate and memory is not released.

WHAT TO DO ABOUT DATA FETCHING

Prefer a library designed for it, rather than effects.

WHY

Caching, deduplication, retries and stale data are handled for you.


Was this answer helpful?
Back

Are you happy with your experience? Leave us a review on Trustpilot.


Trustpilot