DEV Community

yash kumat
yash kumat

Posted on

Redux Basics

This is a guide to understand and use redux in your project in easiest way.

Table of Contents

  1. About Redux
  2. Getting Started
  3. Usage
  4. Contact
  5. Acknowledgments

About Redux

  • Centralize your application's state and logic.

Lessons Learned

1. Reducer - Function that takes current state and action (type of action + data) as an argument and return updated state.

2. Action - Object that has type of action (basically name) and data to be passed to a reducer function.

3. Store - Give us different methods to fetch or modify current state

  * getState() - Returns current state

  * dispatch() - call reducer function by passing action

  * subscribe() - listen to state change
Enter fullscreen mode Exit fullscreen mode

Built With

Getting Started

Prerequisites

  • react
  npx create-react-app app-name
Enter fullscreen mode Exit fullscreen mode
  • redux
  npm install redux
Enter fullscreen mode Exit fullscreen mode

Usage

This is how you can use redux in your application

  1. Create reducer.js file and write function that takes state and action and retuns updated state.
function reducer(state =[], action){
  if(action.type === "type){
    <!--  Some Logic    -->
    return updatedState
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Create store.js file and export store
import { createStore } from 'redux'

const store = createStore(reducer);

export default store;
Enter fullscreen mode Exit fullscreen mode
  1. Now you can use store variable to getState or dispatch (take action) or subscribe (listen to state change), etc
    • getState
  store.getState()
Enter fullscreen mode Exit fullscreen mode
  • dispatch
  store.dispatch({
      type: "type",
      payload:{
          data: "data"
      }
  })
Enter fullscreen mode Exit fullscreen mode
  • subscribe
  store.subscribe(()=>{})
Enter fullscreen mode Exit fullscreen mode

Contact

Email - ykumat@gmail.com
Twitter - @yashkumat
Github Profile: https://github.com/yashkumat/

Acknowledgments

(back to top)

Top comments (0)