100DaysOfCode – Days 13 & 14 – Redux
In Redux, there is a single state object that’s responsible for the entire state of your application. This means if you had a React app with ten components, and each component had its own local state, the entire state of your app would be defined by a single state object housed in the Redux
store. This is the first important principle to understand when learning Redux: the Redux store is the single source of truth when it comes to application state.
- This also means that any time any piece of your app wants to update state, it must do so through the Redux store. The unidirectional data flow makes it easier to track state management in your app.
dispatchmethod is what you use to dispatch actions to the Redux store. Calling
store.dispatch()and passing the value returned from an action creator sends an action back to the store.
- Reducers in Redux are responsible for the state modifications that take place in response to actions. A
actionas arguments, and it always returns a new
state. It is important to see that this is the only role of the reducer.
- Another key principle in Redux is that
store.subscribe(). This allows you to subscribe listener functions to the store, which are called whenever an action is dispatched against the store. One simple use for this method is to subscribe a function to your store that simply logs a message every time an action is received and the store is updated.
- A callback function is simply a function that get’s called after another function is done being executed.
- In order to let us combine multiple reducers together, Redux provides the
combineReducers()method. This method accepts an object as an argument in which you define properties which associate keys to specific reducer functions. The name you give to the keys will be used by Redux as the name for the associated piece of state.
- To include Redux Thunk middleware, you pass it as an argument to
Redux.applyMiddleware(). This statement is then provided as a second optional parameter to the
createStore()function. Then, to create an asynchronous action, you return a function in the action creator that takes
dispatchas an argument. Within this function, you can dispatch actions and perform asynchronous requests.
Now let’s make a mix and starting from tomorrow I’ll learn React with Redux.