State management of front-end applications is increasingly complex. With the advent of the big front end era, the front end pays more and more attention to processing logic, instead of focusing on the IMPROVEMENT of UI level. However, the emergence of the front end framework represented by React greatly simplifies the complexity of writing UI interface. React provides a State mechanism for State management and development conventions such as “State promotion”. However, these solutions are only applicable to small applications. When your front-end application has more than 10 pages, how to control application State and make collaborative development efficient becomes an urgent problem. Redux was born to solve these problems! Redux’s “Unique source of truth for data”, one-way data flow, and “Pure function Reducers” have greatly simplified the front-end logic, enabling us to write arbitrarily complex front-end applications in an efficient and collaborative way. This tutorial aims to explain Redux in a few words, and to grasp the concepts and essence of Redux in practice.

Welcome to the Redux Package series:

  • Redux: How to Fix the React state crisis
  • Redux: Strike while the iron is hot and completely refactor
  • Redux Education Package Association (3) : To perform their respective duties and regain the original purpose

This tutorial is part of the React front End engineer’s learning path. Welcome to Star and encourage us to continue to create better tutorials.

Before we read the tutorial

The Redux documentation defines Redux as a predictable JavaScript application state management container.

This means that Redux doesn’t work on its own, but needs to work in conjunction with a specific View layer front-end framework, including but not limited to React, Vue, or Angular. We’ll use React as the binding view layer here, because Redux was originally created in the React community as a library designed and developed to address React state management issues. This tutorial will give you a sense of React’s “state crisis” and how Redux solves it, so you can learn more about Redux and understand where it came from and where it’s headed.

React Hooks are really catching on these days, showing amazing potential, and some even claimed they could get rid of Redux. Redux’s success is not only due to the framework itself, but also to the ecosystem built around it, such as Enhancers, Middlewares, Redux-form, and Redux-Immutable. There were even top frameworks based on Redux, such as Dva and Rematch, which cemented Redux’s supremacy in the React community.

It is interesting to note that Redux’s React binding library, React-Redux, is currently being refactored with React Hooks to make code more concise and efficient, so I think the React Hooks are still in the early stages. A small number of early adopters are using it in view to build better React projects or frameworks. React Hooks can make those projects and frameworks better and help the Redux ecosystem continue to thrive, so we have reason to believe that with React Hooks, It will make the React community more efficient and professional. It will also help make the Redux toolchain lighter and ultimately a great feature of React that will take React and its ecosystem to the next level.

The premise condition

This tutorial is a quick start on Redux and focuses on how to use it when binding with React. Understanding Redux is an advanced step for a React developer, so we assume that you should have the following knowledge before reading this tutorial:

  • ES6 functions, classes,constHave a good understanding of functional programming, such as pure functions, immutability, etc
  • React has a good understanding of React, especially if you’ve independently developed a React application with at least 5 pages
  • Have some experience with Node and NPM installation dependencies, and follow this tutorial

What will you learn

In this tutorial, we will first give a use the React implement backlog of small applications (more than the last tutorial complete version of the function of the filter), it will be our learning starting point of the story, when you are familiar with the original code, and understand its function, you can close it, then start our tutorial!

Based on the template written in pure React, we will analyze the problems existing in React handling state and the advantages brought by Redux refactoring. Next, we’ll learn how to take a pure React app and rebuild it step by step into a Redux app, and eventually create an updated to-do widget.

The code and the end result

The source code implemented for this tutorial is hosted on Github:

  • React source code:
  • Refactoring source code with Redux: source address.

You can see what the code looks like in the CodeSandbox:

  • Pure React effect: Final effect address.
  • Refactoring with Redux: Last effect address.

Start your Redux tour

Despite all the hype surrounding Redux, it can actually be summed up in a graph that helps you think about the nature of the front end:

Let’s take a look at this image first, and you’ll see it in various forms several times throughout the tutorial. We hope this image will be in your mind when you think of Redux after this tutorial.

View

First we’ll look at the View. In front-end development, we call this the View layer, which is the effect shown to the end user. For this tutorial, our View is React.

Store

As front-end applications have more and more work to do, we put forward requirements for the front-end to maintain “state”. In React, this “state” will be stored in this.state. In Redux, this state is saved in Store.

The Store can be viewed in an abstract sense as a front-end “database” that holds front-end states and distributes them to views so that they can render different content based on those states.

Notice that Redux is a predictable JavaScript application state management container, and that state container is the Store here.

Reducers

The web page we see in our daily life is not static, but responds to user “actions”, whether it is a page jump or login and registration, these actions will change the state of the current application.

In the Redux framework, Reducers serves the purpose of responding to different actions. To be more precise, Reducers are JavaScript functions that are responsible for updating the state in the Store.

Once we have a rough idea of these three core concepts, we can begin to study Redux.

Prepare the initial code

Clone the initial React code template to the repository and switch to the initial-code branch (the initial code template) :

git clone https://github.com/pftom/redux-quickstart-tutorial.git
cd redux-quickstart-tutorial
git checkout initial-code
Copy the code

Install project dependencies and open the development server:

npm install
npm start
Copy the code

The React development server will then open the browser, and if you see the following and can do it, the code is ready:

prompt

Since we’re using the Create React App scaffolding, which uses Webpack Development Server (WDS) as the Development Server, our React App will automatically refresh as we save the file while editing the code.

Exploring the initial code

The to-do widget we completed is a little more advanced than the one we implemented in the previous tutorial, as shown in the following GIF:

We want to show a list of Todos, and when a todo is clicked, it will be marked with a strikeout to indicate that the todo is complete, and we also add an input box so that the user can add new toDos. At the bottom, we show three buttons that switch the type of todo to display.

The React code component is designed as follows:

  • TodoListTo display the todo list:
    • todos: ArrayIs a TODO array in which each element looks similar{ id, text, completed }.
    • toggleTodo(id: number)Todo is a callback function that is called when a todo is clicked.
  • TodoIs a single TODO component:
    • text: stringIs what this todo will display.
    • completed: booleanIs used to indicate whether the element is complete or not, and if it is, the style will mark the element with a delete line.
    • onClick()Is the callback function that will be called when the todo is clicked.
  • LinkIs a button that shows the filter:
    • active: booleanIndicates that the button is selected, so it cannot be clicked
    • onClick()Represents the callback function that will be called when the link is clicked.
    • children: ReactComponentShow child components
  • FooterUsed to show three filter buttons:
    • filter: stringRepresents the selected filter string at this time, which is[SHOW_ALL, SHOW_COMPLETED, SHOW_ACTIVE]One of them.
    • setVisibilityFilter()When Link is clicked, the corresponding clicked will be setfilterThe callback function of.
  • AppThe React root component, which eventually combines the other components and compiles and renders them using the ReactDOM, is used in itsstate> defines properties used by several of the above components, methods used by other components, andnextTodoId.VisibilityFilters.getVisibleTodosAnd so on.

Prepare the Redux environment

We know that Redux works with a variety of view-tier frameworks like React, Vue, and Angular. Redux is just a state management container, so to use Redux in React, we need to install the corresponding dependencies.

npm install redux
npm install react-redux
Copy the code

Well done! Now that you’re all set, you can’t wait to write a bit of Redux-related code. Don’t worry, in the next section, we’ll introduce detailed concepts of the Redux Store and explain what parts of React it will replace with code.

Understand Store: The only true source of data

We mentioned earlier that the Store’s role in Redux is to Store state, which is basically a simple “database” on the front end. In today’s state-rich front-end applications, if every state change (such as clicking a button) had to be communicated to the back end, the average response time for the entire site would be unacceptable and the user experience would be terrible.

According to incomplete statistics: “a website can retain a user’s time is only 8S, if you can’t attract users in 8S, or the website has problems, then you will completely lose the user!”

So in order to accommodate the user’s access needs, the smart front-end pioneers began to introduce the back-end “database” concept into the front end, so that most of the front-end state can be handled directly in the front end, without the intervention of the back end.

React status “Crisis”

In React, we store state in this.state for each component. Each component’s state is private to the component.

We’ll use this picture to illustrate why it’s tedious:

Component A is the parent of components B and C. If component B wants to operate on component C, it first calls the handleClick method passed to it by parent A. It then uses this method to change the state of parent A, which in turn triggers A change in component C via React’s automatic rerendering mechanism.

Now that component B and component C are level, you may not notice any problems with this cross-component change. Let’s look at another diagram:

As we see in the diagram above, component B and component C are many steps apart, and the n in the diagram could be 10 or more. If you want to modify component C in component B at this point, you pass the handleClick method down layer by layer. It’s pretty tedious to call it every time you want to make a change.

The situation becomes even more complicated if component C is further down the hierarchy from component A:

Not only is the handleClick method passed down A very deep level to component B, but when component B calls the handleClick method, it changes the state of component A and passes it back to component C, and all components from component A to component C trigger rerendering. This introduced a huge amount of rendering overhead, which became unaffordable as our applications became more complex.

Deliverer: Store

React was created to write user interfaces better and more efficiently. It shouldn’t or shouldn’t be responsible for state management.

So the tortured frontiersmen came up with the great Store. We do not need to keep the state of each component separately at all. We directly extract the state of all components and construct a centralized state tree by analogy with the React component tree. This state tree corresponds to the React component tree one by one, which is equivalent to the state modeling of the React component tree:

As you can see, we have removed the component’s state and replaced it with a state tree, which is a normal JavaScript object. Using nesting of objects as an analogy to nested composition of components, the state tree modeled by JavaScript objects is the Store in Redux.

Once we pull the state out of the component, it becomes relatively simple and efficient to manipulate component C using component B.

We initiate an action to update state C in component B. The corresponding update function updates the Store state tree and then passes the updated state C to component C to trigger the re-rendering of component C.

As you can see, when we introduce this mechanism, the interaction between component B and component C can be isolated without affecting other components in the React tree. There is no need to pass through the deep handleClick function. There is no need to pass the updated state layer by layer to component C. Performance has a qualitative leap.

With the Redux Store, all state changes in React applications are made to this JavaScript object tree. All state changes are fetched from this JavaScript object tree. The state tree represented by this JavaScript object becomes the “sole source of truth for data” for the entire application.

Wet your hands

Now that we know what Redux Store does for React, let’s immediately apply Redux to React and see how the magic Store can step in and make such a big difference.

We modify the SRC /index.js in the original code template to look like this:

import React from "react";
import ReactDOM from "react-dom";
import App, { VisibilityFilters } from "./components/App";

import { createStore } from "redux";
import { Provider } from "react-redux";

const initialState = {
  todos: [{id: 1.text: "Hello, tootlark.".completed: false
    },
    {
      id: 2.text: "I am a little little tootlark.".completed: false
    },
    {
      id: 3.text: "If small birds, can also show a grand plan!".completed: false}].filter: VisibilityFilters.SHOW_ALL
};

const rootReducer = (state, action) = > {
  return state;
};

const store = createStore(rootReducer, initialState);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>.document.getElementById("root"));Copy the code

As you can see, the above code does the following:

  • We first did the packet guide fromreduxThe deducedcreateStore, fromreact-reduxDerived byProvider, fromsrc/components/App.jsThe deducedVisibilityFilters
  • And then we defined oneinitialStateObject, which will be the initial state data for later Store creation, and the initial value of the JavaScript object tree we mentioned earlier.
  • And then we defined onerootReducerFunction, which is an arrow function, receivesstateactionAnd then returnstate, this function hasn’t done any work yet, but it is one of the parameters required to create a Store, and we’ll cover it in more detail in a later Reducers.
  • Next, we call the Redux API we exported earlier:createStoreFunction, passed in as definedrootReducerinitialState, which generates the hero of this section: Store!
  • And we ended up inAppThe outermost layer of the componentProviderPackage and receive what we created in the previous stepstoreAs an argument, this ensures that we can later access the state in the Store in the child component.Providerreact-reduxReact provides an API that Redux uses to bind Redux to React. This API Bridges the way Redux communicates with React.

Now that we have created the Store, we combine the Store and React components using the Provider provided by the React/Redux library. Let’s take a look at the effects of combining Store and React.

Open SRC /components/ app.js and modify the code as follows:

import React from "react";
import AddTodo from "./AddTodo";
import TodoList from "./TodoList";
import Footer from "./Footer";

import { connect } from "react-redux";

// Omit VisibilityFilters and getVisibleTodos functions...

class App extends React.Component {
  constructor(props) {
    super(props);

    this.toggleTodo = this.toggleTodo.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.setVisibilityFilter = this.setVisibilityFilter.bind(this);
  }

  // omit other methods in the middle...

  render() {
    const { todos, filter } = this.props;

    return (
      <div>
        <AddTodo onSubmit={this.onSubmit} />
        <TodoList
          todos={getVisibleTodos(todos, filter)}
          toggleTodo={this.toggleTodo}
        />
        <Footer
          filter={filter}
          setVisibilityFilter={this.setVisibilityFilter}
        />
      </div>
    );
  }
}

const mapStateToProps = (state, props) => ({
  todos: state.todos,
  filter: state.filter
});

export default connect(mapStateToProps)(App);
Copy the code

As you can see, the code above does these things:

  • First we start withreact-reduxThe binding library surface is exportedconnectFunction.
  • And then at the bottom of the file, we define onemapStateToPropsArrow function, it receivesstatepropsthestateThis is the JavaScript object state tree that we’re holding in our Store, so far the one we defined in the last fileinitialStateContent; thispropsThe React component that we’re familiar withpropsformapStateToPropsIs an optional parameter.mapStateToPropsFunctions are primitives that operate on components at the same timepropsAnd the Store state, which is then merged into the final component props (of course we didn’t use the content of the original component props here) and passedconnectFunction is passed toAppComponents.
  • connectThe function to receivemapStatePropsFunction, getmapStatePropsReturns the state of the final composition and then injects it intoAppComponent, return a new component, and hand inexport defaultThe export.
  • After the work above, we are inAppComponent can be fetched throughmapStateToPropsThe returned{ todos, filter }Content, we deconstruct through objects, fromthis.propsgettodosfilterProperties.
  • Finally we delete what is no longer neededconstructorIn thethis.stateThe content.

Pay attention to

Connect is a higher-order function, which is a function that takes arguments and returns another function. Here connect returns a new function by receiving mapStateToProps and calling it. This new function then receives the App component as a parameter, injecting the todos and filter properties through mapStateToProps. Finally, return to the injected App component.

prompt

The reason we can get the JavaScript object state tree saved in the Store from the App component through mapStateToProps is because we wrapped the App component with the Provider. The Store is passed to the Provider as a property.

Reproduce the Redux ring diagram

Take a look at the loop diagram we mentioned in step 1. We are now at the beginning of the process, passing the state from the Store to the View using Connect in the React Redux binding library.

Save the changes. If your React development server is open, you should see something like this in your browser:

Congratulations to you! You’ve already written Redux’s Store, and done about a third of your work integrating Redux into React. By adding Store to React, you successfully unblock the data between Redux and React and remove this.state, replacing this.state with Store state.

But! When you click the Add Todo button at this point, your browser should display a red error because we removed the this.state content, so reading this.state.todos in the onSubmit method will result in an error. Don’t worry, we’ll explain how to resolve these errors in the next section: Action.

Understand Action: The only way to change State

Welcome to the Redux Action. Let’s once again refer to the figure from the previous section:

In the last section, we did something in component B to change the content in component C. We took a close look at the downside of a completely React implementation. We introduced the concept of a Redux Store and explained that we only need to build a global JavaScript object state tree. Then all state changes are accomplished by modifying the state tree, passing the modified new state to the corresponding component and triggering re-rendering. We also showed how to pass state in Store to the React component.

In this section, we’ll talk about how to modify the state stored in the Redux Store. Let’s throw out the familiar ring diagram of Redux states:

Modifying the stored state in Store is the second part of the diagram above, that is, we have created the Store and stored a JavaScript object state tree in it, and we modify the stored state in Store by “initiating an update action”.

What is Action?

In Redux’s conceptual terms, there is one and only way to update the Store’s state: call the Dispatch function and pass an action to that function.

An Action is a simple JavaScript object:

{ type: 'ADD_TODO'.text: 'I am a little tookie' }
Copy the code

We can see that an action contains the type of the action and the data required to update the status, where type is mandatory and other contents are optional. Here we add a text in addition to type, which means that we initiate the action with type ADD_TODO. An additional text content is passed.

So if we need to update the Store state, we need a function call like the following:

dispatch({ type: 'ADD_TODO'.text: 'I am a little tookie' })
Copy the code

Use Action Creators

Because when we create an Action, sometimes some content is fixed. For example, the Action of our todo add tutorial has three fields, namely type, text and ID. We may need to dispatch this Action in multiple places. So each time we need to write the following long string:

{ type: 'ADD_TODO'.text: 'I am a little tookie' , id: 0}
{ type: 'ADD_TODO'.text: 'If you're a bird, you can make a difference.' , id: 1}... {type: 'ADD_TODO'.text: 'Welcome to the Tooquine community! ' , id: 10}
Copy the code

Those of you familiar with JavaScript functions probably know how to solve this problem. Yes, we just need to define a function and pass in the parameters that need to be changed.

let nextTodoId = 0;

const addTodo = text= > ({
  type: "ADD_TODO".id: nextTodoId++,
  text
});
Copy the code

This function, which receives some parameters that need to be modified and returns an Action, is called Action Creators in Redux.

After using Action Creators to create the Action, we wanted to modify the Store’s state so that it looked like this:

dispatch(addTodo('I am a little tookie'))
Copy the code

As you can see, our logic is greatly simplified. Each time we initiate a new “ADD_TODO” action, we only need to pass in the corresponding text.

Integrate with the React

Now that you know the basics of Action, let’s try out how to initiate update actions in React.

First, we created the Actions folder under the SRC folder, then created the index.js file under the Actions folder, and added the following Action Creators to it:

let nextTodoId = 0;

export const addTodo = text= > ({
  type: "ADD_TODO".id: nextTodoId++,
  text
});
Copy the code

Since we will need to create a large amount of Action or Action Creators for the Redux React app, best practice in the Redux community recommended that we create a separate Actions folder. And write the specific Action logic in this folder.

As you can see, we added an addTodo Action Creator that takes the text argument, increments it with an ID each time, and returns an Action with an ID and text of type “ADD_TODO”.

Then we modify SRC/components/AddTodo js file, the onSubmit before replacing to dispatch (action) to modify the state of the Store in the form of:

import React from "react";
import { connect } from "react-redux";
import { addTodo } from ".. /actions";

const AddTodo = ({ dispatch }) = > {
  let input;

  return (
    <div>
      <form
        onSubmit={e= >{ e.preventDefault(); if (! input.value.trim()) { return; } dispatch(addTodo(input.value)); input.value = ""; }} ><input ref={node= > (input = node)} />
        <button type="submit">Add Todo</button>
      </form>
    </div>
  );
};

export default connect()(AddTodo);
Copy the code

As you can see, the code above makes these changes:

  • First we start withreact-reduxThe deducedconnectFunction, which is responsible for injecting the state from the Store into the component, but also passes an additional method to the component:dispatch, so that we can in the component ofpropsTo get this method. Notice that we use object destructuring to fetch in the AddTodo functional componentdispatchMethods.
  • Exports the one we just createdaddTodoThe Action of Creators.
  • And then we use useaddTodoreceiveinput.valueEnter the value to create a"ADD_TODO"Action, and usedispatchThe function sends this Action to Redux and asks to update the contents of the Store. Updating the state of the Store requires Reducers, which we will explain in detail in Reducer.

Since we’ve changed onSubmit to dispatch an Action instead of directly modifying this.state, we remove the SRC /components/ app.js code because we don’t need them anymore:

import React from "react";
import AddTodo from "./AddTodo";
import TodoList from "./TodoList";
import Footer from "./Footer";

import { connect } from "react-redux";

// omit VisibilityFilters and getVisibleTodos...

class App extends React.Component {
  constructor(props) {
    super(props);

    this.toggleTodo = this.toggleTodo.bind(this);
    this.setVisibilityFilter = this.setVisibilityFilter.bind(this);
  }

  toggleTodo(id) {
    const { todos } = this.state;

    this.setState({
      todos: todos.map(todo= >
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    });
  }

  setVisibilityFilter(filter) {
    this.setState({
      filter: filter
    });
  }

  render() {
    const { todos, filter } = this.props;

    return( <div> <AddTodo /> <TodoList todos={getVisibleTodos(todos, filter)} toggleTodo={this.toggleTodo} /> <Footer filter={filter} setVisibilityFilter={this.setVisibilityFilter} /> </div> ); }} // No change after...Copy the code

You can see that we removed nextTodoId because we had redefined it in SRC /actions/index.js; Next we remove the onSubmit method; Finally, we remove the onSubmit method passed to the AddTodo component.

To save the changes, we typed in the input box of the To-do widget and then clicked the Add Todo button. We found that the previous error did not appear again.

Leave a note of regret

In this section, we completed the second part of the Redux state circular chart, which is called the Launch of update actions. We first explained Action and Action Creators, and then launched an update of the State in the Store with dispatch(Action).

Once we used dispatch(action), the methods we passed to the child to change the parent’s State were no longer needed, so we removed them from the code. In our AddTodo, that method is onSubmit.

Unfortunately, although we have deleted the onSubmit method, the dispatch(Action) mentioned and implemented in this section can only accomplish half of the function of the previous onSubmit method, namely initiating the modification action, but we cannot modify the state in the Store yet. To change the State in the Store, we need to define Reducers that respond to our Dispatch actions and modify the corresponding data in the Store according to the requirements of the Action.

Understand Reducers: Respond to the directives of actions

In this section, we will immediately address the regret left in the previous section, which is that we seem to have fired an airshot, dispatched an Action, and achieved nothing.

Let’s start with our omnipotent Redux state cycle:

Now that we have completed the first two steps, there is only one final step left before Redux is integrated into React, which is to dispatch the Action from the component and update the state in the Store, which is called Reducers in the concept of Redux.

Purification of Reducers

Reducer is a normal JavaScript function that accepts two parameters: state, which is the state tree of the JavaScript object stored in the Store, and action, which is the action we dispatch in the component.

reducer(state, action) {
  // Operate on state
  return newState;
}
Copy the code

Reducer perform corresponding operations on the state according to the instructions of the action and return the state after the operation. Redux Store will automatically save this new state.

Pay attention to

The official Redux community’s agreement on reducer is a pure function, that is, we cannot directly modify state, but can use {… } and other object destructions return a modified new state.

For example, if we modify state = {a: 1, b: 2} to replace a with 3, we should do this: newState = {… State, a: 3}, not state. A = 3. This type of modification does not directly modify the original object, but returns a new object modification, which we call “purified” modification.

Prepare to respond to Action changes

Once we understood the concept of Reducer, we immediately responded to the actions we dispatched before in the application to make up for the regrets we left in the previous section.

Open SRC /index.js and make the following changes to rootReducer:

// ...

const rootReducer = (state, action) = > {
  switch (action.type) {
    case "ADD_TODO": {
      const { todos } = state;

      return {
        ...state,
        todos: [
          ...todos,
          {
            id: action.id,
            text: action.text,
            completed: false}}; }default:
      returnstate; }};// ...
Copy the code

The code above does a few things:

  • As you can see, we have the previousrootReducerMake improvements from simply returning the originalstateAnd became oneswitchStatements, inswitchStatement for actiontypeMake a judgment, and then make the corresponding processing.
  • whenaction.typeThe type of"ADD_TODO"When, we fromstateTo retrieve thetodosAnd then use{... }Grammar totodosAdd a new element object and setcompletedProperties forfalseIndicates that the todo is not complete and finally passes through one layer{... }Syntax will be newtodosMerge into the oldstateIn, return this newstate.
  • whenaction.typeThere is no matchingswitchFor any condition, we return the defaultstateSaid,stateThere are no updates.

After making the changes to the rootReducer function, Redux can respond to actions dispatched from the component using the Reducer function, Currently we can only respond to actions with action.type “ADD_TODO”, which indicates a new todo.

Save the code, open your browser, type something in the input box, and then hit the Add Todo button. Now the page should respond correctly to your actions and we can happily Add new items to our to-do list.

summary

In this section, we have implemented the first Reducer that can respond to the actions from the component dispatch. It determines the types of action.type and “purified” the state according to these types. When action.type does not match any of the Reducer types, we return the original state.

After knowing the three concepts of Redux: Store, Action and Reducers, let’s look at another picture:

We’ve seen something like this before, only this time we’ve added something to it, highlighting the work done by Dispatch, Reducers, and Connect, respectively.

  • dispatch(action)Used to issue directives in the React component to change the Store state. When we need to add a new to-do item, it replaces the one previously defined in the componentonSubmitMethods.
  • reducer(state, action)Use this instruction to modify the portion of the Store that corresponds to the Store state. When we need to add a new to-do item, it replaces the one previously defined in the componentthis.setStateOperation.
  • connect(mapStateToProps)Used to pass the updated data to the component, which then triggers React to re-render to show the latest state. It provides a data communication bridge between Redux and React.

Now that you’ve learned all the core concepts of Redux, our application is fully integrated with Redux. However, one thing we have not done is refactor the entire application completely using Redux. In the next tutorial, we’ll use what we’ve learned in the previous three sections to step by step rebuild the rest of our to-do application into Redux, so read on.

Want to learn more exciting practical skills tutorial? Come and visit the Tooquine community.