A Simple React + Redux example
It took me awhile to understand how Redux worked. Here is a very simple example that hopefully will help you if you’re in the same situation.
The App
Here’s what it does:
- There’s a list of posts.
- Each post has an ID, title and a button.
- You click the button in one of the posts and that post’s title is updated.
The State
[code]
{
appName: ‘app’,
posts: [
{
id: 0,
title: “Test title”,
description: “description”
},
{
id: 1,
title: “Test title”,
description: “description”
}
]
}
[/code]
The Components
There’s two components:
App Component
https://gist.github.com/pmqa/8cec9477954f417bd7a637c790ea723c
Posts Component
https://gist.github.com/pmqa/9bb341d7e68835acba3481567facfc27
These are all the files that matter. The source code is here. Take a look at it.
Redux – The theory
We should use Redux when there are deeply nested components that need to update state at the highest level, eg. state that is shared by components. If your app is simple enough maybe you won’t need Redux.
- Actions are usually triggered by events in your app and they send data to the store.
- Actions are plain objects of data.
- Reducers update the state of your app based on actions.
- The Stores store the state of your app.
- You connect the Store to each component of your app. Doing this, you can update your app’s state from any component.
- mapDispatchToProps will be used to dispatch actions to the reducers.
The click in our App
When a click happens in our app, an action is dispatched to the reducer that updates the state.
The Action
[code]
const mapDispatchToProps = dispatch => ({
updatePostTitle: (payload) =>
dispatch({ type: UPDATE_POST_TITLE, payload })
});
[/code]
The payload is a reference to the post object where the click happened. The payload is just another way to say data. That’s all it should be, data that reducer needs to know to update the state we need to update.
Reducer
https://gist.github.com/pmqa/3064d4766c293b3b203893faa450dfa5
I use dot-prop which is just a helper to make sure all the updates to state are done without mutating it first.
The Conclusion
Hopefully, the process of updating state with Redux become more clear. If you have anything to point out, you are more than welcome to do so in the comments. Thanks for reading!