React is an amazing library, no doubt about it. But every library has it’s own quirks that make us all go “If only that one thing was done better…”.
For me, that quirk is having to invoke a callback function from a child component in order to change the state of it’s parent component. Now this doesn’t seem so troublesome when it’s just the two layers deep, but imagine having to pass down props through numerous child components and having a chain of callbacks being fired so the parent component can receive the callback and update the state accordingly. Now imagine having to keep track of multiple props that fire multiple callbacks across multiple components. That to me, sounds like the definition of hell.
So enter Reflux. Reflux is a framework for an architechtural pattern called Flux. I won’t get too much into Flux on this post, check out the official docs to learn more.
Basically Reflux helps us keep track of our application state so that instead of passing around numerous callback functions, we can instead trigger events and have certain React components who need the data of those events listen for the triggers; bypassing the middle man completely!
(The middle in this case being all the other components that the callbacks would normally have to flow through to reach it’s destination)
Here’s a small and not so bad example of the callback hell I was mentioning:
So here we can already see that even with only two levels of child component, we’re having to tediously pass props (handleChangeName) around as functions so a callback chain can reach the parent component to change the state of name. Imagine doing this on a production scale application. Not ideal at all.
Here’s how we would approach the same situation in Reflux:
So as you can see here, we are no longer having to pass props around to invoke callbacks in order to change parent state.
TL;DR Anytime we have to change a state on a distant parent component, we simply call an action which will trigger a store function. The store will do it’s calculation and trigger it’s own event, which React components can listen to, and those components that are listening will automatically receive the new data, without us having to manually pass the data through callback props.
Reflux is an amazing tool and I’ve only begun to take a look at it, so I’m sure that I’ll post more about it in the future! Until then, have fun Reacting!