redux tutorials code example

Example 1: what is redux

What is Redux?

Redux is a pattern and library for managing and updating application state, 
using events called "actions". It serves as a centralized store for state 
that needs to be used across your entire application, with rules ensuring 
that the state can only be updated in a predictable fashion.

Example 2: redux

Redux is a state management library
1 Create Initial State
2 Define Action Types
3 Define Action Creators
4 Create Reducers
5 Change the initial State
6 Pass the parameters to the Creator function and the reducers

Code
// Initial State

const initialState = {
  todos: [
    {
      text: "eat food",
    },
    {
      text: "Exercise",
    },
  ],
};

// Action Types
// create a simple action type

const ADD_TODO = "ADD_TODO";

// ACtion creators

function addTodo(text) {
  return {
    type: ADD_TODO,
    payload: text,
  };
}

//create reducers
function todoReducer(state = [], action) {
  switch (action.type) {
    case ADD_TODO:
      return [...state.todos, { text: action.payload }];
    default:
      return state;
  }
}

console.log("Initial State : ", initialState);

// Lets make changes to initial states
const action = addTodo("Make it work");
const newState = todoReducer(initialState, action);

console.log(newState);

Tags:

Misc Example