store.js
import {configureStore} from '@reduxjs/toolkit'; const initialState = {counter: 0, showCounter: true}; const counterReducer = (state =initialState, action) => { if (action.type === "increment") { return {...state, counter: state.counter + action.payload}; } else if (action.type === "decrement") { return {...state, counter: state.counter + action.payload}; } else if (action.type === "toggle") { return {...state,showCounter: !state.showCounter} } return state; } export const store = configureStore({ reducer: counterReducer });
Counter.js
import {useSelector, useDispatch} from 'react-redux'; function Counter() { const counter = useSelector(state => state.counter); const showCounter = useSelector(state => state.showCounter); const dispatch = useDispatch(); return ( <div> {showCounter && <div>Counter : {counter}</div>} <div> <button onClick={() => dispatch({type: "increment", payload: 1})}>+1</button> <button onClick={() => dispatch({type: "decrement", payload: 1})}>-1</button> <button onClick={() => dispatch({type: "toggle"})}>Toggle</button> </div> </div> ); } export default Counter;