Redux Actions: Beginner's Guide

Redux Actions: Beginner's Guide

React Redux is one of the two ways to handle dynamic data and API calls in React. Unlike HTML, you cannot call APIs directly in react due to its ability to constantly re-render the page. Hence, to update state effectively in React, Redux, and context APIs are used. In this article, we will dig into Redux and will leave the context API for some other time.

Redux

getting-started-with-redux-1096x453.png

According to the official documents, "Redux is a predictable state container for JavaScript apps." The statement means that you can create a container to manage your states through redux. But more important is the word "predictable". As react involves a lot of states and its re-rendering, it is difficult to predict the update of the states in a complex application.

Redux acts as an outer layer or a box that stores the states and functions globally. If you want to call a function/state to be used somewhere, you need not drill down every component passing it through props.

[ Note:- It is just an explanatory blog to get you familiar with the concepts of redux. For code and installation guide, visit Redux's website. ]

Actions

As the name suggests actions are the part of the redux that do "something". Essentially, the action contains all the functions that are needed to be executed and all the APIs that are needed to be called. As per the official document, they are the only source of information for the store.

A redux action has two components:- i) Type ii) Payload

Type is the kind of request that you want to process. The type is used with a switch case to ensure that the correct function is called for every state update.

Payload is the data that is being sent to the reducers to process. Payload gives the data to the reducers to act upon and convert it into meaningful data.

const action = {
  type: "TEST_USER",
  payload: {user: "Testing", age: 30},
}

This is a general convention to use all the caps separated by a "_" for an action TYPE. Moreover, you can also write API calls to functions inside the actions. But, after all of this, there is just one thing that you must remember to do. It is to dispatch the action and the payload. It is crucial to dispatch your action and payload for the smooth functioning of redux. Your code in this case would look like this.

export const someFunction = ()=>{
   // Code to do something and change some data

dispatch({type: TEST_USER, payload: user});
}

What is dispatch? Well, let's wait for the next blog to know about dispatch and reducers. Comment down your thoughts about the blog.