Replacing Redux with the new React context API

February 25, 2018 0 Comments

Replacing Redux with the new React context API

 

 

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.

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.

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.

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.

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

I̶ ̶h̶a̶v̶e̶ ̶n̶o̶t̶ ̶f̶o̶u̶n̶d̶ ̶a̶ ̶s̶e̶x̶y̶ ̶n̶a̶m̶e̶ ̶f̶o̶r̶ ̶i̶t̶ ̶y̶e̶t̶,̶ ̶b̶u̶t̶ ̶i̶f̶ ̶y̶o̶u̶ ̶h̶a̶v̶e̶ ̶a̶n̶ ̶i̶d̶e̶a̶ ̶f̶o̶r̶ ̶i̶t̶ ̶p̶o̶s̶t̶ ̶y̶o̶u̶r̶ ̶s̶u̶g̶g̶e̶s̶t̶i̶o̶n̶s̶ ̶h̶e̶r̶e̶ ̶o̶r̶ ̶s̶e̶n̶d̶ ̶m̶e̶ ̶a̶ ̶t̶w̶e̶e̶t̶.̶ ̶F̶o̶r̶ ̶n̶o̶w̶ ̶i̶t̶’̶s̶ ̶o̶n̶l̶y̶ ̶a̶v̶a̶i̶l̶a̶b̶l̶e̶ ̶v̶i̶a̶ ̶G̶i̶t̶h̶u̶b̶.̶

yarn add react-waterfall

🤓

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


Tag cloud