Back

Hooks and Application State

Sharing state across components is one of the most common problems in React, since there is no out-of-the-box solution.

There is a plethora of paradigms and libraries: Flux and its countless implementations, Context, Zustand, ...

Functional components and hooks bring new constraints and tools, further proliferating possible approaches.

This section explores navigating application state in React on top of functional components and hooks - without a state framework.

Examples

Raw hooks: the problem

Native react hooks - like useState - do not come with an out of the box way of sharing state across components

The example below has 2 components that share a stateful hook; the data is not shared.

Naive hooks as storage
  • 2 components sharing the same hook
  • State is isolated - each will have an independently updated copy
Click to increment: 5
Click to increment: 5

Ad hoc solution

Ad hoc shared state through hooks
  • Self-managed state synchronization across views
  • State is shared - either component will update the shared state
Click to increment: 5
Click to increment: 5

Conclusions

React does not prescribe a method of sharing state across functional components.

Hooks allow simple ad hoc solutions - but in a production app, it's worth evaluating existing approaches like Zustand, which take care of common concerns like persisting application state.