DEV Community

Cover image for Basics of Redux
Dostonbek Oripjonov
Dostonbek Oripjonov

Posted on • Edited on

7 2

Basics of Redux

Table of contents

What is Redux

Redux is state managament library. Common use cases of Redux with user interface libraries like React, Vue or Angular. Howerver, you can add this library to your any web project to control your global state. More

Lifecycle methods of redux

Definitions

Action creator is function that creates or returns plain javascript object.
Action is plain javascript object. So, Action creator returns Actions. Actions must have type which defines purpose of action and optionally payload which contains data.

// Action creator                 // Action
const myActionCreator = value => {type : "INCREASE_TO_ONE", paylaod : value }

dispatch is function that take action and makes copies of this object. It is built in function.

Reducers are functions which take suitable action according to type of action which is dispatched and updates state.

// Reducer
const myReducer = (prevState = null, action) => {
 if(action.type === "INCREASE_TO_ONE"){
    prevState = action.payload + 1;
    return prevState;
 }
 return prevState;
}

State is actual state value of your application;
Below given example to use Redux

// import built in libraries from redux
import {createStore, combineReducers} from 'redux'

// Action creator                 // Action
const myActionCreator = value => {return {type : "INCREASE_TO_ONE", paylaod : value }} ;

// Reducer
const myReducer = (prevState = 0, action) => {
 if(action.type === "INCREASE_TO_ONE"){
    prevState = action.paylaod + 1;
    return prevState;
 }
 return prevState;
}

const combinedReducers = combineReducers({value : myReducer})
const store = createStore(combinedReducers);
const action = myActionCreator(6);
// use case of dispatch function
store.dispatch(action);

console.log(store.getState());

Test that code in codesandbox.io

That is it !!!

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (1)

Collapse
 
dastnbek profile image
Dostonbek Oripjonov

React & Redux soon !!!

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay