Skip to main content

Rect Context can be Dangerous!

Use Context with CAUTION

Context is not a replacement for global state. It can cause visible performance problems.

Problem with context

When the context value changes, react does not know which components are using the context values, So it forces re-render of the entire component tree wrapped in that context. HUGE PERFORMANCE PROBLEM

How do 3rd party global state libraries work?

Yes "redux" and all the global state management libraries use React's context internally one way or another, so a lot of developers, even very experienced ones think we can ditch the 3rd party libraries and use Context directly.

But Redux doesn't expose the states through context, it'd be a problem like explained above!

It only exposes the useSelector and useDispatch hooks through context, these hooks are just javascript functions that never ever change, never get re-created, or redefined or updated.

The functions remain same. And it's these functions that know how to find the needed piece of state from global state. These hooks know which components have subscribed to which states, and which components triggered the state update, so redux can determine which components need to be re-rendered. There is a lot of engineering in there!

Where Context Makes Sense

  • Context is suitable for use cases where we have minimal writes and tons of reads.
  • Rule of thumb: If the context value can change more than twice, use a dedicated global state management system, don't use context.
    • e.g. App Theme: current theme can be stored in a context and all the components can have access to the value. When the context value changes, all the components do need re-rendering.
  • Rule of thumb: If the context only affects a very small portion of the application tree, go ahead, otherwise use a dedicated global state management system.