Codementor Events

Replacing Redux with the new React context API

Published Mar 19, 2018Last updated Sep 15, 2018

The new context API that comes with React 16.3 is pretty neat. It was built in the render props style trending over these last months. Let’s explore it:

It’s pretty nice right? Let’s go further with Flux-like implementation.

What’s Flux ?

This talk from the excellent Jing Chen has revolutionized how we think about our applications today. If you want to know what Flux is as a concept, take a look here.


A basic Flux representation

One library has democratized this concept: Dan Abramov’s Redux and its legendary time travel demo at React Europe 2015.

Implementation

With the createContext() API example above, we already have the unidirectional Store → View in place.

What we need is actions and dispatchers to dynamically update the store. What if our dynamic store was just the state of a root React component?

We have just passed state and actions as values of the provider. And now we can get it with <Consumer />.

I created a library to have everything we need to use this data flow easily while keeping great performance.

react-waterfall


Example repository available here

Just import initStore from react-waterfall, set your initial state, and take some actions: **(state, …arg) → stateChunk **— ** ** and you’re good to go.

The created store gives you some cool things like:

  • The enhanced Provider and Consumer presented above
  • actions (you can access them from Consumer , too)
  • getState() to get the current state
  • connect()() to map state and actions to component props
  • subscribe() to react to state changes

As you can see, connect is not exactly the same as you have in React-Redux. Here you just have to pass an array of the state chunks you want. It will filter your state and prevent unwanted re-rendering.

At this time, react-waterfall enforces you to have a flat state, like when using normalizr.

If you need deeper selectors and/or memoized computed data, you can, of course, use reselect . Check out this example here.

If you want time travel, it’s possible 🚀 to just run this example. The implementation is right here.

Comparison with Redux

Pros

  • Easier to implement
  • Weight and performance
  • Cleaner action return with state chunk (as in setState)

Cons

  • No native deep selectors (you can use reselect)
  • No Redux DevTools integration (for now)
  • It only works with React ^16.3

You want to try it ?

I have not found a sexy name for it yet, but if you have an idea for it post you suggestions here or send me a tweet. For now it's inly available via Github.

yarn add react-waterfall

🤓


If you don’t want to miss any of my articles, follow me on twitter @DidierFranc

Discover and read more posts from Didier FRANC
get started
post commentsBe the first to share your opinion
Show more replies