Elegant state management

 @rahulgaba16 → ReactFoo-VueDay Pune 2020

React Logo

Using Context API + Hooks

Rahul Gaba

UX Engineer @ Google

Elegant state management

React Logo

Using Context API + Hooks

 @rahulgaba16 → ReactFoo-VueDay Pune 2020


  • Why state management?

  • Benefits of redux

  • Problems with redux

  • Context, Providers and Consumers

  • The useReducer Hook

  • Benefits of Context API + Hooks

  • When to use what?

Why state management?

  • Sharing data
  • Caching data
  • Separation of concerns


Benefits of redux

  • Separation of concerns.
  • Share data between multiple components.
  • Cache data between multiple routes.
  • Time travel debugging.
  • Structured way to maintain the code.

Problems with Redux

  • What to store in redux? Shared data/Persistent data?
  • Keeping something in store and then realising that it shouldn't have be there.
  • Too much of a boilerplate.
  • Too many things to read about.

Problems with Redux

Context, Providers and Consumers.

Context & Provider


Two most important hooks

Consumer with useContext

The useReducer Hook

Building a cart


Provider with reducer

Where to use Providers?


5 Reasons to use redux

  1. Sharing data 
  2. Caching data 
  3. Separation of concerns
  4. Middlewares*
  5. Ease of debugging*

Advantages over Redux

Advantages over Redux

  • Have module level "stores" (Chunking)

  • Use reducer only if you feel it's necessary.

  • Very easy to move logic from a component to a Provider.

  • Incremental, composite way of doing things.


Providers + useReducer

<Component />
<Component />
<Component />
<Component />
<Component />
<Component />

Module level Providers
<b>Module level Providers</b>
Provider A
[Not supported by viewer]
Provider B
[Not supported by viewer]
Reducer A
Reducer A
Reducer B
Reducer B


  • No middleware support
  • Limited SSR support
  • Too many render cycles*
  • No time travel debugging

When to use What?

Use Context API + Hooks when...

  • You don't need middlewares
  • An easy and straightforward way to manage state.
  • Solve the 3 basic things of state management
  • Planning to Migrate to another state management library in future is a bad idea.
  • Example:

Use Redux when...



  • One file exports both context instance and provider.
  • Create Module level context for sharing module-level state.
  • `useContext` hook provides a very convenient and cleaner way to use multiple contexts in a component.
  • Avoiding the bad parts of redux: Solve present problems instead of problems which might occur in future.
  • Use latest dev tools to debug context.
  • `useReducer` is meant to replace `useState` when the state logic is complex.


Thank you!

 @rahulgaba16 → ReactFoo-VueDay Pune 2020


Made with Slides.com