Redux with React

NOTE: YOU HAVE TO READ REDUX ARTICLE AT FIRST

1. Installistion

npm i redux react-redux

2. Create the store

  • At first we define the reducer and pass the initState
const reducer = (state = initState , action) => { //some actions logic return state; }
  • Then we need to create the store and pass the reducer the store;
import {createStore} from 'redux'; const store = createStore(reducer); export default store;

3. Subscribe the app in the store

import {Provider} from 'react-redux'; <Provider store={store}> <App /> </Provider>

4. Get the state from the store

import {useSelector} from 'react-redux'; // the callback function work like .map callback function const state = useSelector((state) => {return state});

5. Dispatch an action

import {useDispatch} from 'react-redux'; // the callback function work like .map callback function const dispatch = useDispatch(); dispatch({type:"type-1"})

Redux toolkit

1. Installistion

Existing App

npm install @reduxjs/toolkit

New App

npx create-react-app my-app --template redux

2. createSlice

import { createSlice } from '@reduxjs/toolkit' const mySlice = createSlice({ name:'slice-name', initialState:{ value:0 }, reducers:{ increment:(state , action) => { state.value++ }, decrement:(state , action) => { state.value--; } } });

2. createStore

import { createStore } from '@reduxjs/toolkit' const store = createStore(mySlice.reducers);

3. Dispatch action

import {useDispatch} from 'react-redux'; const dispatch = useDispatch(); dispatch(mySlice.actions.increment(payload));

3. Create store with multiple reducers

import { configureStore } from '@reduxjs/toolkit'; import counterReducer from './counterSlice'; import showAndHideReducer from './showAndHideSlice'; const store = configureStore({ reducer: { counter: counterReducer, showAndHide: showAndHideReducer } }); export default store;