Getting ready

Before anything else, we must install a couple of packages: redux, the state-managing package itself, and the react-redux bindings for using Redux with React. (You can use Redux with other frameworks or libraries, but this is not covered in this book.) Installation is simple, just use npm, as we have done several times before:

npm install redux react-redux --save

We'll have to learn several concepts in order to use Redux

  • Store: The only place ("single source of truth") where you hold the application state. You create the store globally, at the beginning of your application, and then you connect components to it. Connected components will get re-rendered when the state changes, and everything they need to render themselves should come from the store. The store can only be updated through actions.
  • Actions: Objects that your components dispatch with any new data you wish. Actions always have a type attribute to distinguish different types, and any other data, with no restriction. Actions are usually created by action creators to simplify coding, and after being dispatched they are processed by reducers.
  • Reducers: Pure functions (meaning, no side effects!) that change the application's state, depending on the data received in actions. The state is never modified; rather, a new state must be produced with whichever changes were necessary. The reducer produces a new state as a function of the old state and the data received in the action.

This is shown in the following diagram:

Data flow in Redux is strictly uni-directional, always following a circular pattern

Using this flow cycle helps keep the state and the view in sync—since the latter is produced in terms of the former, and all updates to the state immediately cause the view to be updated. We have installed the necessary tools to use, and we know what we have to do; now, let's get to an actual example.

You may want to look at eslint-plugin-redux, which gives you some rules for how to get the best out of Redux. Check it out at https://github.com/DianaSuvorova/eslint-plugin-react-redux, and if you're interested, add some or all of its rules to your ESLint configuration; by default, they are all disabled.

In this recipe, let's do a simple example to show most of the concepts in the previous section. After reading multiple articles and tutorials on the web, I think it's mandatory to provide some kind of example involving a counter, and let's not break that tradition and do it here too! We want to have a counter that we can modify by clicking on some buttons, and we also want to know how many clicks we've made.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset