In this course you learn how to use Redux as a state manager in your React applications

Last update: Jul 25, 2022

React + Redux course

In this course you learn how to use Redux as a state manager in your React applications.

With Redux you can access your data easily and save them. In this project I used Material UI. If you want to learn about MUI, I have a small project you can check this out here.

Redux

So, Redux is a state manager you can use with React, Vue and even Vanilla. Redux has 4 important thingg.

  • Reducers
  • Actions
  • Store

Reducers

Reducers are functions that take the current state and an action as arguments, and return a new state result. In other words, (state, action) => newState.

Creating a reducer is as simple as you can see down below:

data !== action.payload); default: return state; } }">
// src/redux/reducers/todo.js
const todoReducer = (state = [], action) => {
    switch (action.type) {
        case "ADD_TODO":
            return state.concat(action.payload);
        case "DELETE_TODO":
            return state.filter(data => data !== action.payload);
        default:
            return state;
    }
}

When we have several reducers, we need to combine them in a variable.

Create an index file in src/redux/reducers. Now combine all reducers:

// src/redux/reducers/index.js

import { combineReducers } from "redux";

const allReducers = combineReducers({
    todo: todoReducer,
});

Actions

Actions are plain JavaScript objects that have a type field. As mentioned earlier, you can think of an action as an event that describes something that happened in the application.

To create an action, create actions directory inside redux directory. I added all actions in index.js. You can store actions in their files.

{ return { type: "DELETE_TODO", payload: todo, }; }">
export const addTodo = (todo) => {
    return {
        type: "ADD_TODO",
        payload: todo,
    };
}

export const deleteTodo = (todo) => {
    return {
        type: "DELETE_TODO",
        payload: todo,
    };
}

Store

The Redux store brings together the state, actions, and reducers that make up your app. The store has several responsibilities:

  • Holds the current application state inside
  • Allows access to the current state via store.getState();
  • Allows state to be updated via store.dispatch(action);
  • Registers listener callbacks via store.subscribe(listener);
  • Handles unregistering of listeners via the unsubscribe function returned by store.subscribe(listener).

Where to create or store? open index.js that is in src.

import { createStore } from "redux";

import allReducers from './redux/reducers';

let store = createStore(allReducers);

So, now we have the store that is created. How to provide this store inside the whole app. We use Provider.

);">
import { createStore } from "redux";

// Import Provider
import { Provider } from 'react-redux';

import allReducers from './redux/reducers';

let store = createStore(allReducers);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    // Add provider with store as prop
    <Provider store={store}>
        <App/>
    </Provider>
);

Done! You now had set up Redux.

Local Storage

When you setup Redux, it will only store the data until you don't refresh the app. When you refresh the app or open it in another tab, the data will be start over.

So, what should you do? The best way is to store data in localstorage. But, how to do it?

Follow these steps:

  • Create storage directory in redux directory
  • Add load and save functions
  • Integrate localstorage in redux

I imagine you created the localstorage file in storage directory inside redux and start from second step.

Create state name

You add a key variable to use for entire file.

const key = 'redux';

Add load function

export const loadState = () => {
    try {
        const serializedState = localStorage.getItem(key);

        if (serializedState === null) {
            return undefined;
        }

        return JSON.parse(serializedState);

    } catch (error) {
        return undefined;
    }
};

Add save function

export const saveState = (state) => {
    try {
        const serializedState = JSON.stringify(state);
        localStorage.setItem(key, serializedState);
    } catch (error) {
        // die
    }
};

Integrate with Redux

Open index.js in src.

Now import them:

import { loadState, saveState } from "./redux/storage/localstore";

Ok, create a variable that represent data from localstorage.

const persistedState = loadState();

Edit the createStore with represented data:

let store = createStore(
    allReducers,
    persistedState
);

Last step, saving data. Now you should do something that update the state in localstorage. We will use saveState().

store.subscribe(() => saveState({
    todo: store.getState().todo
}));

Application

This is a very simple app. There is a Floating action button that open the add dialog like thus:

Here, you enter the name.

Add

Also, you can select what color you want.

Colors open

If your storage be empty, you will see this:

No task

But, here are some stuff I had added.

All tasks

BTW, Application is responsive :)

  • In tablet Tablet

  • In mobile Mobile

GitHub

https://github.com/BlackIQ/react-redux-tutorial
You might also like...

Approach to the main concepts of Redux and its use

Approach to the main concepts of Redux and its use

Projeto para estudo - Redux / Redux Saga Conteúdo O que o Redux resolve ? O Redux possui três Princípios Single source of truth State is read-only Cha

Apr 9, 2022

A simple app for study react with redux, redux saga and typescript.

React com Redux, Redux-Saga e TypeScript. 🚀 Uma aplicação simple para entender o funcionamento do Redux e a melhor maneira de utiliza-lo junto com o

May 24, 2022

Redux - Create forms using Redux And React

Redux - Create forms using Redux And React

Exercício de fixação Vamos criar formulários utilizando Redux! \o/ Antes de inic

Jul 21, 2022

A chart monitor for Redux DevTools https://www.npmjs.com/package/redux-devtools-chart-monitor

A chart monitor for Redux DevTools https://www.npmjs.com/package/redux-devtools-chart-monitor

Redux DevTools Chart Monitor This package was merged into redux-devtools monorepo. Please refer to that repository for the latest updates, issues and

May 3, 2022

Dead simple state management for React

Undux & TypeScript TodoMVC Example TodoMVC for Undux Installation git clone [email protected]:bcherny/undux-todomvc.git cd undux-todomvc npm install npm

Aug 10, 2020

Create the next immutable state by mutating the current one

Immer Create the next immutable state tree by simply modifying the current tree Winner of the "Breakthrough of the year" React open source award and "

Aug 4, 2022

This is a simple react project that Stores the books, When the user enter any book with the category will be updated in the API and you can get someof books from API based on the category. 📚

Book Store React 📚 This is a simple react project that Stores the books, When the user enter any book with the category will be updated in the API an

May 31, 2022

An i18n solution for React/Redux and React Native projects

An i18n solution for React/Redux and React Native projects

redux-react-i18n An i18n solution with plural forms support for Redux/React Workers of all countries, unite! Supported languages list with expected co

Sep 30, 2021

Official React bindings for Redux

React Redux Official React bindings for Redux. Performant and flexible. Installation Using Create React App The recommended way to start new apps with

Jul 31, 2022
Redux Bucheli Course Strategies Passing Store Data Through The Top Level React Component

Redux Bucheli Course Strategies Passing Store Data Through The Top Level React Component

Jan 22, 2022
Redux Tutorial - share my experience regarding redux, react-redux and redux-toolkit
Redux Tutorial - share my experience regarding redux, react-redux and redux-toolkit

Redux Tutorial 1. Introduction to Redux 1.1 What is Redux & why Redux? A small JS Library for managing medium/large amount of states globally in your

Jul 28, 2022
A lightweight state management library for react inspired by redux and react-redux

A lightweight state management library for react inspired by redux and react-redux

Apr 1, 2022
A Higher Order Component using react-redux to keep form state in a Redux store
A Higher Order Component using react-redux to keep form state in a Redux store

redux-form You build great forms, but do you know HOW users use your forms? Find out with Form Nerd! Professional analytics from the creator of Redux

Aug 2, 2022
redux-immutable is used to create an equivalent function of Redux combineReducers that works with Immutable.js state.

redux-immutable redux-immutable is used to create an equivalent function of Redux combineReducers that works with Immutable.js state. When Redux creat

Aug 5, 2022
This command line helps you create components, pages and even redux implementation for your react project
This command line helps you create components, pages and even redux implementation for your react project

react-help-create This command line helps you create components, pages and even redux implementation for your react project. How to install it? To ins

Apr 6, 2022
Manage the state of your React app with ease

@spyna/react-store React app state management that uses a storage Demo https://spyna.github.io/react-store/ Install npm install --save @spyna/react-st

Jan 19, 2021
Skeleton React App configured with Redux store along with redux-thunk, redux persist and form validation using formik and yup

Getting Started with React-Redux App Some Configrations Needed You guys need to modify the baseUrl (path to your server) in the server.js file that is

Jul 10, 2022
:recycle: higher order reducer to add undo/redo functionality to redux state containers
:recycle: higher order reducer to add undo/redo functionality to redux state containers

redux undo/redo simple undo/redo functionality for redux state containers Protip: Check out the todos-with-undo example or the redux-undo-boilerplate

Aug 1, 2022
Financial Metrics - about building a mobile web application to check a list of metrics that I create making use of React and Redux

Financial Metrics is about building a mobile web application to check a list of metrics (numeric values) that I create making use of React and Redux

Jun 4, 2022