Basic Data Flow in Redux
This week we’ve started working with React and Redux — it’s been a lot to take in so I wanted to take this opportunity to sketch out the basic flow of data when using Redux.
Redux helps us mange the state of our app by providing us with one centralized location for the state, a simple system to manage state modifications, and a mechanism to ‘subscribe’ to state updates.
Redux has three main principals:
- The state of the entire application is stored within a single object called the store — this is know as the single source of truth.
- The state is read-only — the only way to update the state is to send an action which describes what event happened.
- The state tree can only be transformed by pure functions called reducers.
A reducer simply a function that specifies what the state should be after receiving two pieces of information: the previous state of your application and an action object. It will compare the action it receives against all of the actions it has defined internally; if there is a match, it will return a new object of what the state should be set to. If there is not a match, it will return the previous state (unmodified).
The reducer function is located inside of the store — what is the store you might ask. It has three main functions defined inside of it: getState, dispatch, and subscribe. Store is responsible for keeping track of the state of your app, so it has a getState method that you can call that simply returns the state object. Dispatch is the function that is used to set the applications state, it passes through whatever action is provided as an argument into the previously provided reducer function and then sets the state to it’s return value. Finally there is subscribe, this takes functions in as arguments and calls them whenever an action is dispatched — this is how we can call the render function whenever the state is changed.
When an application is run for the very first time, the createStore method is called with the argument of the reducer function. The dispatch method will be invoked with an empty action object as an argument to force the default value from the reducer to be returned, and thus set as the initial state.
Dispatching an Action
Let’s say we want to change this state of the app because a button was just clicked — we need to dispatch an action! This would be done by running the following line of code:
This is a very simple example; action creator functions are typically used to generate action objects — these can accept arguments and pass additional information along with the action object.
The dispatch function will now pass the action object along with the previous state to the reducer function. The returned value will be assigned as the new state and all functions that are stored in the subscribed collection will be called upon, which will re-render the page.
Here is a simplified version of what happens in a Redux application (specific to the store).