React

React – Redux Basics

Overview This article helps to understand some fundamental concepts of redux. This article also explains how can we set up any project...

Written by Shivangi Rajde · 3 min read >
React - Redux Basics

Overview

This article helps to understand some fundamental concepts of redux. This article also explains how can we set up any project which uses plain react and redux for state management. We will also configure react and redux for a project.

Redux

Redux is a state management tool for any JavaScript application. We need to use React redux as we are using redux with React, so we need to bind our react components with redux so that our components can read data from the Redux store and actions can be dispatched for updating the data in the store.

Fundamentals of Redux

State

A state is a JavaScript object. It can only be updated by dispatching an action.

Actions

Actions are the only way by which we can send the data to the store. Actions are plain JavaScript object that describes the change.

An action object must have a type that indicates the type of action being performed and other properties of the object can be added as required.

Example

{    
   type: DEMO_ACTION,    
   payload: “Data to be passed”    
}

We can write actions in ways like:

export const demoAction = () => dispatch => {    
dispatch({    
   type: DEMO_ACTION,    
   payload: “data”    
   })    
};

This action will dispatch the action to type DEMO_ACTION and we are passing the payload with the type property.

Action Creators

Action creators are the functions that create actions, or we can say functions that return action.

Example:

function demoAction(payload)     
{     
return {      
   type: DEMO_ACTION,     
   payload,    
   }    
}   

Dispatch()

The dispatch function lets you dispatch an action to change the state of your application. For understanding the working of the dispatch function we can pass the result of the action to the dispatch() to initiate it.

Example:

dispatch(demoAction(payload))

When using the helper like connect() of React-Redux, you can use bindActionCreators() to automatically bind many action creators to a dispatch( ) function.

Example:

export function demoAction(payload) {     
return     
{    
   type: DEMO_ACTION,    
    payload    
   }    
} 

Reducers

Reducers are simply pure functions. A function that calculates the next state tree based on the previous state tree and the action being dispatched. It’s called a reducer because it’s the type of function you would pass to

Array.prototype.reduce(reducer, ?initialValue)

Redux will call our reducer with an undefined state for the first time.

Example:

function demoApp(state = initialState, action) {    
switch (action.type)     
{     
   case DEMO_ACTION:    
    return Object.assign({}, state, { visibilityFilter: action.filter })       
    default:     
   return state     
   }     
} 

Store

A store is just an object which has few methods. An application has a single store, which can further be decomposed rather than multiple stores. A store can be created using createStore( ).

Example:

import { createStore } from 'redux';    
import demoApp from './reducers';    
const store = createStore(demoApp);   

For making our store available to our application components we need to pass that store in the provider as shown below. We need to make these changes in our index.js file so that store is available to our application.

Example: (index.js)

import React from "react";    
import { render } from "react-dom";    
import { BrowserRouter as Router } from "react-router-dom";    
import App from "./app/App";    
import store from "./app/configureStore";    
import { Provider } from "react-redux";    
        
render(    
<Provider store={store}>    
  <Router>    
    <App />    
  </Router>    
</Provider>,    
document.getElementById("app")    
);    

Connect()

Connect is a function provided by the React-Redux which helps us to connect the React component with the Redux store.

The connect function doesn’t modify the component passed, it just wraps the component passed and returns the new connected component class, which helps us to get the pieces of data passed and the functions it can use to dispatch actions to the store.

Example:

Import ….    
class componentName extends Component {    
}    
export default connect(mapStateToProps, mapDispatchToProps)(componentName);   

Here, the first argument passed to connect function, mapStateToProps selects the part of data from the store that the React component needs as the state of the store changes. It is a simple function that returns an object that the component needs.

MapDispatchToProps is a function that lets you dispatch an action when that function is called.

When to use redux?

When working on small projects with a simple tree structure, it is easier to maintain the states of the components and pass the data between the components. For this, the data needs to reside in a single component so that it can be passed on to the sibling components. The method(s) needed to update the state also need to reside in the parent component and pass to the sibling components as props.

But what if the tree gets complex? For passing data in components that are far apart in the tree, do we still need to pass the data to all the components in between the parent component and the child component which needs the data?

The state will have to be lifted to the nearest parent component and to the next until it gets to an ancestor that is common to both components that need the state and then, it is passed down.

So, conclusively, state management gets messy when the app gets complex. Here comes the need to use state management tools such as Redux.

Take a real-time example of a situation when we will need to use Redux for managing the state of the application.

Let’s take the example of the Facebook profile. When you update your profile picture from your Edit Profile page, on saving, it should also update the profile picture wherever it is used in your profile. By using the approach of simple React, there needs to be some relation between the component of the edit profile and other components so that the image updates everywhere. If we use this approach, it would be messy to maintain the structure of the project and route the data passed in the components.

Summary

After reading this article, we are now able to understand the basics of React and Redux. We also have an understanding of redux terms used when working with react and redux.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *