“There are patterns which emerge in one's life, circling and returning anew, an endless variation of a theme”
― Jacqueline Carey, Kushiel's Chosen
This is a quick tl;dr on why Redux is used.
When I first got started at using React, people kept talking about this whole Redux shenanigans. I had no clue what it was for and why it was used. I really wished someone could've given me a brief overview on what it was, what it's used for, and the problem it solves.
The problem with ReactJS is that it only renders the view. There isn't a built in way to handle states between components and complex data manipulation between the view-layer binding. Yes, you could pass down states from the parent component and have event handlers bubble up. Yeah, you could access lower states by using refs and stuff. But it's confusing. It makes your code hard to read and understand to see what's going on.
To make things easier, enter flux.
Flux is more like a "mentality" than a framework. The goal is to have data flow one way. How it works is, you have your state. You dispatch an action to create a copy of your previous state (except with the things you changed). And when that new store is created your view updates. Your data store is never touched by the view. There's a bunch of different implementations of flux.
Redux is basically a very lightweight, extremely efficient implementation of flux. It offers a clean way to map properties in the data-store whenever anything happens with props passed into a child component. It also lets you access and change (not exactly; but I'll get to it in a bit) using UI events instead of traversing all the way up the component tree.
How does Redux actually work?
Redux uses a function called a reducer that takes in two parameters: An action and the previous state and it returns the modified state. Reducers have to be pure functions. That means that the output is only determined by the input. No matter how many times you run the function with the same parameters, it will output the same thing. That means the reducers don't mutate the previous state. They create a new state each time. This allows for easy debugging because it lets you follow your state back to see every change that's happened.
And there you go. Hopefully this answered a few questions for budding React users on what Redux is and what it's used for. If you expect your application to have a complex state that gets manipulated alot, I'd recommend looking into Redux.
Now, if you think you need Redux for your application. Dan Abramov (the creator of Redux) has a fantastic course on Egghead that you can learn how to actually use it.
- ReactJS is ONLY the view.
- A central state to store everything makes things easy.
- Redux IS that central state.
- Dispatch Action -> Reducer -> Create a new Store -> Update view
- Reducers must be pure functions. They don't store state, they don't mutate state. They are passed a state and return a new one.