17. Redux Toolkit - florypaul/ReactJS GitHub Wiki

https://github.com/academind/react-complete-guide-code/tree/18-diving-into-redux

Step 1: Install

npm i react-redux npm i @reduxjs/toolkit

Step 2 - In root create a "store" folder and create index.js file. Create other dependent reducer/slice JS files example: ui-slice.js, cart-slice.js

Step 3 - In store/index.js file import configureStore to combine the reducer/slice JS files and to export store.

import { configureStore } from '@reduxjs/tookit'; import uiSlice from './ui-slice'; import cartSlice from './cart-slice';

// configureStore to reducer (slice files) const store = configureStore({

reducer :{ ui: uiSlice.reducer, cart: cartSlice.reducer } });

export default store;

Step 4: In main index.js

  1. file wrap provider pass store to the main App component
  2. import store file

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

Step 5: Create reducer/slice JS files with the default state and actions.

  1. Create Slice - give a name, initialState and reducer with an object and include your actions in there.
  2. Give reducers function
  3. export actions

example: ui-slice.js

import uiSlice = createSlice( { name: 'ui', initialState: {cartIsVisible : false}, reducers: { toggle(state){ state.cartIsInvisible = !state.cartIsVisible } } });

export const uiActions = uiSlice.actions; export default uiSlice;

Step 6 - in main App component use useSelector to access the state from store

import { useSelector } from 'react-redux';

const showCart = useSelector(state => state.ui.cartIsInvisible)

{ showCart && <Cart />}

Step 7 - From the component dispatch the action to reducer function first import useDispatch and uiActions from slice/reducer file

import { useDispatch} from 'react-redux';

const dispatch = useDispatch();

const toggleHander = () => { dispatch(uiActions.toggle());

}

⚠️ **GitHub.com Fallback** ⚠️