# Redux with React **NOTE: YOU HAVE TO READ [REDUX ARTICLE](https://hackmd.io/@abdQaddora/redux) AT FIRST** ## 1. Installistion ```jsx= npm i redux react-redux ``` ## 2. Create the store - At first we define the reducer and pass the initState ```jsx= const reducer = (state = initState , action) => { //some actions logic return state; } ``` - Then we need to create the store and pass the reducer the store; ```jsx= import {createStore} from 'redux'; const store = createStore(reducer); export default store; ``` ## 3. Subscribe the app in the store ```jsx= import {Provider} from 'react-redux'; <Provider store={store}> <App /> </Provider> ``` ## 4. Get the state from the store ```jsx= import {useSelector} from 'react-redux'; // the callback function work like .map callback function const state = useSelector((state) => {return state}); ``` ## 5. Dispatch an action ```jsx= 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** ```jsx= npm install @reduxjs/toolkit ``` **New App** ```jsx= npx create-react-app my-app --template redux ``` ## 2. createSlice ```jsx= 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 ```jsx= import { createStore } from '@reduxjs/toolkit' const store = createStore(mySlice.reducers); ``` ## 3. Dispatch action ```jsx= import {useDispatch} from 'react-redux'; const dispatch = useDispatch(); dispatch(mySlice.actions.increment(payload)); ``` ## 3. Create store with multiple reducers ```jsx= import { configureStore } from '@reduxjs/toolkit'; import counterReducer from './counterSlice'; import showAndHideReducer from './showAndHideSlice'; const store = configureStore({ reducer: { counter: counterReducer, showAndHide: showAndHideReducer } }); export default store; ```