Introduction to Redux (Action, Reducers and Store)

Redux is a state managing library used in JavaScript apps. It simply manages the state of your application or in other words, it is used to manage the data of the application. It is used with a library like React.

Uses: It makes easier to manage state and data. As the complexity of our application increases. At the start, it is hard to understand but it really helps to build complex applications. In starting, it feels like a lot of work, but it is really helpful.

Before we dive into Redux we should know about some important principles of redux. There are three principles of Redux these are:



  • Single source of truth: It helps to create universal apps. The state of the application is stored in one object tree called store. It means one app, one store.
  • State is read-only (Immutability): It means that we don’t change the state object and its properties directly. Instead of this make a new object, recalculate the new application state and update it with our newly created object. And this is important because all the changes are happening in the same place so everything is needed to be done in strict order and one by one.
  • Changes are made with pure functions (reducers): Reducers are pure functions that take previous state and action (discuss later) and return the new state.

Building Parts of redux:

  1. Action
  2. Reducer
  3. Store

Actions: Actions are a plain JavaScript object that contains information. Actions are the only source of information for the store. Actions have a type field that tells what kind of action to perform and all other fields contain information or data. And there is one other term called Action Creators, these are the function that creates actions. So actions are the information (Objects) and action creator are functions that return these actions.

Example: The easiest example we can take try is To-do. So we will create two action creators one for adding a task in to-do and for removing.

filter_none

edit
close

play_arrow

link
brightness_4
code

function addTask(task) {
    
  return {
      
    type: 'ADD_TODO',
    task: task
  }
}
  
function removeTask(task) {
   
  return {
    type: 'REMOVE_TODO',
    task: task
  }
}

chevron_right


So, the above two functions are action creators. One is for adding a task and one for removing, and see both have a type which tells what is the purpose of actions creator and they will be used with reducers.

Reducers: As we already know, actions only tell what to do, but they don’t tell how to do, so reducers are the pure functions that take the current state and action and return the new state and tell the store how to do.

Let’s create a reducer for our TO-do.
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

function task(tasks = [], action) {
    
  if (action.type === 'ADD_TODO') {
    return [...tasks, action.task];
  } else if (action.type === 'REMOVE_TODO') {
      return tasks.filter(task => task !== action.task);
    }
  return tasks;
}

chevron_right


So, In the above reducer, a function created with two arguments first is the current state and next is the action we want to perform, First initialize the current state empty array because at first task list is gonna be empty.
Then check the action type, different type of actions will have different functionality, In the above case if task is added, then it returns the array containing older list of task and with one new added, but the older state are not gonna mutate the older state we gonna return new one, this is needed to be kept in mind. Same for remove, if none of the above two then just return the list. Return the new state, Never mutate the older state.
For more complex apps use combineReducers() to combine them so that it can pass to store.

Store: The store is the object which holds the state of the application.

Functions associated with Store:

  • createStore() – To create a store
  • dispatch(action) -To change the state
  • getState() – for getting current state of store.

Example: Let’s create a store for our TO-do.

filter_none

edit
close

play_arrow

link
brightness_4
code

import { createStore } from 'Redux';
  
// Creating store
const store = createStore(taskList);
  
// Here add is action as you can see console,
// its an object with some info
const add = addTask('Wake up');
console.log(add);
  
// Dispatch usually trigger reducer and preform task
store.dispatch(add);
  
// getState() function is used to get current state
console.log(store.getState());
  
store.dispatch(addTask('Study'));
store.dispatch(addTask('Eat'));
store.dispatch(addTask('Go to sleep'));
store.dispatch(removeTask('Eat'));
store.dispatch(addTask('Work'));
store.dispatch(addTask('Sleep'));
store.dispatch(removeTask('Sleep'));
  
console.log(store.getState());

chevron_right




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai