Should we use Redux within a React App? – Most probably yes as many different containers within your app may need access to the same data which comes from an API or simply from a parsed CSV. What is a container anyway? A container is an evolved form of a React Component that knows about and is connected to Redux.
Here is a diagram created explaining the flow:
Lets put this diagram into some context.
Imagine an application which displays a list of users. What happens when?
- Our container loads up and calls a fetch users action (as we need the users)
- The fetch users action performs an API call to a users service.
- Once the API call is competed, the action is dispatched along with a type and a payload (returned data) across all of the reducers
- Each reducer analyses the type of action which has just happened. If one of the reducers contains the type used for the fetch users action, it will return the actions payload which contains the updated data (the users list as opposed to having an empty array)
- The component receives within the mapStateToProps an updated fetch users action payload.
- If the container returns updated users data from this mapStateToProps function then it will be re-rendered 🙂
This method above explains how a list of users is loaded upon app launch or route change, but how can we manually trigger an action that does not dispatch an action upon container launch. The scenario we will take is updating one of these users on an edit user route (/users:id)
- Normally we have the user already loaded in the state as a dispatch event has already occurred on loading the user on the page within the container
- Local container state (props) have already been mapped to the form elements within the JSX ex. First name, last name, phone number
- The admin updates some user information ex. address which locally updates the containers state.
- Admin clicks save which has an onClick handler assigned
- The function calls a user update action that takes the local container state and performs a PUT request to the API
- The user update action is dispatched after a successful update on the server
- All reducers analyse the action and an updated state is returned by the reducer concerned
- Containers receive the updated application state. If the updated application state changes the local container state, then the render method is called to display the updated data.
- An example of a container that would re-render would be a notification container that displays “User X has successfully been updated”
Two scenarios have been explained here.
- On container launch (Loading a list of users)
- Manual action trigger (Updating a user)
If you have any comments, then feel free to leave one at the end of this article. If you want to contact me personally then feel free by using my contact page.