Be reassured, we are not talking about Wordpress Loop here, but about the base concept of Redux: its loop. The main goal of the library is to manage a store, your local database, and distribute the data across various contexts of your application.
type . When any actions are fired, our last entity, the reducers, will check those types and conditionally mutate the Store.
Store and sub-stores
combineReducers that will “split” your Store into sub-stores. It's still Objects accessible though the Store, but in the future you will be able to choose which one to access in your consumer.
year value in a
First we need to define our initial state: the default value of our time sub-store.
Then, our action.
Now, our reducer to mutate the Store.
And finally the Store itself with the Redux Devtools for debugging clarity.
We can see that the binding uses
.dispatchto bind our action
.getStateto retrieve data
.subscribeto listen store mutations
If you are using react-redux to bind your Redux Store with your React components props, you will use something like:
If you try to do anything other than directly returning an Object in your action, you will have an error like:
This error is pretty clear: Redux requires middleware to deal with async actions. There are a lot of very popular middleware libraries out there and personally my favorite is redux-thunk.
To enable redux-thunk (and still keep Redux Devtools), you must refactor your Store definition after installing
Now you can create asynchronous actions!
Here is a very simple example:
As you can see, your action doesn't return an object anymore, but a function. This function takes
dispatch as first parameters; the method to return your object or trigger another action when your asynchronous logic is over.
Here is a more complex example using axios with loading and error handling:
About others libs
There are two kinds of Redux users: those who loves Redux for what it is and those who loves Redux, but not its “boilerplate code”. The second group use libraries like redux-actions to reduce the amount of code required by a Redux infrastructure. It seems to be a good idea, but in the end, trust me, it will make your code harder to understand because of this useless layer of abstraction.
There is also more “complex” middleware libraries available like redux-saga or redux-observable. They are great libraries, but they will add another big layer of complexity to your app. So be sure to really need it instead of redux-thunk before using it.
My final advice: “never fight Redux boilerplate code, embrace it”. And just take a look to similar store management using MobX or Apollo with local mutations, there is not that less code ^^'.
Three years later and a lot of concurrent libraries, Redux is still not dead! It's still a great state management libraries, regardless of the UI library or framework that you're using. It's great strength is the clarity of its (boilerplate) code and it's amazing debugger.