Knowledgebase

State and the Rules of Hooks Print

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

Managing data in components.

WHAT STATE IS FOR

Data that changes and affects what is displayed.

WHAT NOT TO PUT IN STATE

Values derivable from other state Values that do not affect rendering

WHY

Derived state duplicates a source of truth, and the copies diverge.

WHAT TO DO INSTEAD

Compute it during rendering.

WHAT THE RULES OF HOOKS ARE

Call them at the top level of a component, never inside conditions or loops Call them only from components or other hooks

WHY

React identifies them by call order, and varying it breaks the association.

WHAT UPDATING STATE DOES

Schedules a re-render. It does not change the value immediately.

WHAT THAT CAUSES

Reading the value straight after setting it, and seeing the old one.

WHAT TO DO WHEN UPDATING BASED ON THE PREVIOUS VALUE

Use the function form, which receives the current value.

WHY

Several updates in one event otherwise operate on a stale value.

WHAT TO KEEP STATE AS

The minimum that describes the interface.

WHAT TO LIFT

State needed by several components, to their nearest common ancestor.


Was this answer helpful?
Back

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


Trustpilot