Redux, Flux, and the React Hooks API
Which should I use?
Okay, the title to this article is actually a bit misleading… flux
is an architecture pattern that can be implemented using either the redux
library or the React hooks
API.
There are really two questions you should be asking:
- Do I need flux?
- Should I use Redux or the hooks API to manage state?
Do you need Flux?
Flux libraries are like glasses: you’ll know when you need them. — Dan Abramov
I think there are 3 good reasons to use Flux:
- Your app is complex and flux is a viable way to reduce complexity.
- You’re in an enterprise or business situation where stability is valued over speed of implementation.
- You like front-end code that lends itself to functional patterns and is very testable.
The following is from the Redux docs but I think it is equally true about Flux: “[about Redux] It’s not designed to be the shortest or fastest way to write code. It’s intended to help answer the question “When did a certain slice of state change, and where did the data come from?”, with predictable behavior.”
If you are already using the standard state
and props
in React, you should probably continue doing so unless it’s getting messy and unmanageable.
Do you need Redux or the Hooks API?
If you don’t need a flux pattern, use the hooks
api: https://reactjs.org/docs/hooks-intro.html. It will be the simplest and most productive.
If you do want to use Flux Patterns, you can do so with either redux
or the useReducer
api in React.
For me the deciding factor is middleware. If you make heavy use of tooling centered around Redux, you might be a little disappointed if you switch to useReduce
.
Otherwise, useReducer
is a great, minimalist, no frills flux
implementation. The simplicity is refreshing.
Further Reading
Whenever deciding architecture of a new React app, I always seem to fall back to React AJAX Best Practices by Andrew Farmer. Highly suggest reading this article that has aged very well.