In my previous article about Redux – #explianMeLikeIm5 I tried to explain redux basics as easy as possible. This article continues Redux topic but tells about how to use Redux with React .
How to use Redux in React?
You need to import
react-redux package to your project first. It provides a way for you to pass Redux
dispatch to your React components as
Now, enough theory, let’s get to practice.
Below we have a class component which has
state and 2 methods. It renders
list of messages on the page. When the user types in some text, this text is being added to the state input (
handleChange()). When the user press Submit button, the text is being added to the state messages and appears on the page (
submitMessage()). Simple as that.
Now we need to move the state and any logic connected to the state into Redux store. The only thing which your component will be doing is render DOM elements and messages on the page.
Here is our Redux store implementation:
The next step is to provide React access to the Redux store and the actions it needs to dispatch updates. React Redux provides its
react-redux package to help accomplish these tasks.
React Redux provides a small API with two key features:
The Provider is a wrapper component from React Redux. It allows to access the Redux store and dispatch functions throughout the component. It takes two props:
- the Redux store
- your app
Defining the Provider for an App component might look like this:
So, for our DisplayMessage component we can write Provider like this:
In order Provider works correctly, we need to specify precisely what
action we want. This way we make sure that each component only has access to the state it needs. We accomplish this by creating two functions:
mapStateToProps() does exactly what its name suggests: it connects a part of the Redux state to the props of a React component:
mapDispatchToProps() does something similar, but for actions – it connects Redux actions to React props. This way a connected React component will be able to send messages to the store:
This seems like a lot to do, but once you understand whats going on, it will surely became not that complicated 🙂
Now we have everything ready to connect our React component to Redux store. To handle this task we use method
connect from react-redux.
Connect() takes two optional arguments –
mapDispatchToProps(). They are optional because you may have a component that only needs access to
state but doesn’t need to
actions, or vice versa. If you omit one of the functions, you put
null instead as argument.
So, to connect our DisplayMessage component to the Redux store, we write the
connect method like this:
And we are done! Congratulations! Now you have learned React Redux 🙂