Skip to content
Related Articles

Related Articles

Explain Action’s in Redux

View Discussion
Improve Article
Save Article
  • Last Updated : 01 Mar, 2022

In this article, we are going to learn about Action in Redux. Actions are plain JavaScript object that contains information. Action is one of the building blocks of Redux. 

Redux is a state managing library used in JavaScript apps. It is used to manage the data and the state of the application.

Uses of Redux: With the help of redux it is easy 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.

This was the small brief about redux. Now, we will discuss the Action object.

Action: Actions are JavaScript object that contains information. Actions are the only source of information for the store. It basically carries a payload of information from the application to the store. It only tells us what has happened.  Actions have a type property that they must include as type property tells what kind of action to perform. Action can also contain the payload(data field in the action) to describe the action.

Syntax:

const Actions = {
 type: '',
 payload: ''
}

In the syntax, the Action object has two properties. The first property is “type property” it should be defined in string constraint and It is compulsory to include the type property in the object. The second one is “payload”, Payload stores the additional information about what happened. It is not a compulsion to include “payload” in the object. It is entirely up to you but we should always try to pass only the necessary information to the action object and try to keep it as light as possible. 

As said above, action is the only source of information for the store. Now, we will discuss the store.

Store: The store is the object which holds the state of the application. See, it contains the state of the components which need to be passed to other components. The store makes this passing along much easier as we no longer need to maintain a state inside a parent component in order to pass the same to its children components.

Functions associated with Store:  

createStore(): This method is used to create a store. Below is the syntax for it.

const store = createStore()

dispatch(action): To change the state, we need to call the store.dispatch() and pass in an action object. Below is the syntax for it.

store.dispatch({ type: 'Action' })

getState(): This method is for getting the current state of the store. Basically, after dispatching the action, the store will run its reducer function (a pure function that takes the current state and action and returns the new state, and tell the store how to do it). and save the new value inside it. Then we will call the getState() method to retrieve the updated value of the application.

Action Creators

Action creators are the function that creates actions. So actions are the information (Objects) and action creator are functions that return these actions. These functions help to achieve reusability. For example, An to-do list will have this action creator.

Javascript




// Creating Action creator
function AddToDo(task) {
  return { type: 'ADD_TASK', task: task }
}
  
// Dispatching 
store.dispatch(AddToDo('anything'));

But what if we have multiple action creators how will we bind multiple action creators to store. For that redux have bindActionCreators() method. This is a utility function that takes an action creator or a whole object of action creators and binds them all to the dispatch function that we got from a store. For example, An to-do list will have multiple action creators.

Javascript




const boundToDoActions = bindActionCreators(
  {
    add: AddToDo,
    remove:RemoveToDo,
    clear:ClearToDos
  },
  store.dispatch
)

Creating React Application and Module Installation:

Step 1: Create a React application using the following command:

npx create-react-app MyApp

Step 2: After creating your project folder i.e. MyApp, move to it using the following command:

cd MyApp

Step 3: Once you are done creating the ReactJS application, install redux and react-redux using the following command:

npm install redux react-redux

Project Structure: It will look like the following:

GFG

Example: In this example, we have created two buttons one will increment the value by 2 and another will decrement the value by 2 but, if the value is 0, it will not get decremented we can only increment it. With Redux, we are managing the state.

Filename: App.js

Javascript




import React from 'react';
import './index.css';
import { useSelector, useDispatch } from 'react-redux';
import { incNum, decNum } from './actions/index';
  
function App() {
  const mystate = useSelector((state) => state.change);
  const dispatch = useDispatch();
  return (
    <>
      <h2>Increment/Decrement the number by 2, using Redux.</h2>
      <div className="app">
        <h1>{mystate}</h1>
        <button onClick={() => dispatch(incNum())}>+</button>
        <button onClick={() => dispatch(decNum())}>-</button>
      </div>
    </>
  );
}
  
export default App;

Filename: index.js

index.js




export const incNum = () => {
    return { type: "INCREMENT" }
}
  
export const decNum = () => {
    return { type: "DECREMENT" }
}

Filename: src/reducers/func.js

func.js




const initialState = 0;
  
const change = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 2;
    case 'DECREMENT':
      if (state == 0) {
        return state;
      }
      return state - 2;
    default:
      return state;
  }
};
  
export default change;

Filename: src/reducer/index.js

index.js




import change from './func'
import { combineReducers } from 'redux';
  
const rootReducer = combineReducers({
    change
});
  
export default rootReducer;

Filename: Store.js

Javascript




import { createStore } from 'redux';
import rootReducer from './reducers/index';
  
const store = createStore(rootReducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ &&
    window.__REDUX_DEVTOOLS_EXTENSION__());
  
export default store;

Filename: src/index.js

index.js




import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { Provider } from 'react-redux';
import App from './App.jsx';
import store from './store';
  
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root'),
);

Step to run the application: Open the terminal and type the following command.

npm start

Output:

Reference: https://www.geeksforgeeks.org/introduction-to-react-redux/


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!