A Simple React + Redux example

Posted on Thursday, January 11th, 2018

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


{
appName: 'app',
posts: [
{
id: 0,
title: "Test title",
description: "description"
},
{
id: 1,
title: "Test title",
description: "description"
}
]
}

The Components

There’s two components:

App Component

Posts Component

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


const mapDispatchToProps = dispatch => ({
updatePostTitle: (payload) =>
dispatch({ type: UPDATE_POST_TITLE, payload })
});

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

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!