npx create-react-application counter
npm install redux npm install react-redux npm install @reduxjs/toolkit
export default function counterReducer(state = {counter : 0}, action) { switch (action.type) { case "increment": return {...state, counter : state.counter + 1} case "decrement": return { ...state, counter: state.counter - 1 } case "incrementBy": return { ...state, counter: state.counter + action.increment} default: return state; } }
import { configureStore } from '@reduxjs/toolkit' import counterReducer from './counterReducer' export default function getStore() { return configureStore( { reducer : counterReducer } ) }
import React from 'react' import {useDispatch, useSelector } from 'react-redux' export default function Counter() { const counter = useSelector(state => state.counter) // get counter from state const dispatch = useDispatch() return ( <> <h1>{counter}</h1> <button onClick={() => dispatch({type : 'increment'})}>Increment</button> <button onClick={() => dispatch({type: 'decrement'})}>Decrement</button> <button onClick={() => dispatch({type: 'incrementBy', increment : 10})}>Increment By 10</button> </> ) }
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import getStore from './store' import Counter from './Counter'; import { Provider } from 'react-redux' const store = getStore() // Create store and get it ReactDOM.render( <Provider store={store}> // Associate store with all child components <Counter /> </Provider>, document.getElementById('root') );