Component communication in React (react18) 06 – redux-toolkit + react-redux

Component communication in React (react18) 06 – redux-toolkit + react-redux

    • 1 Introduction
    • 1.1 redux and react-redux
    • 1.2 About redux-toolkit
      • 1.2.1 Official website
      • 1.2.2 Why use Redux Toolkit?
    • 1.3 Install Redux Toolkit
    • 1.4 Redux Toolkit related APIs
  • 2. Starting example – official website example
    • 2.1 Create Redux Store
    • 2.2 Provide Redux Store for React
    • 2.3 Create Redux State Slice
      • 2.3.1 counterSlice.js file
      • 2.3.2 Compare previous action and reducer
    • 2.4 Add Slice Reducers to Store
    • 2.5 Using Redux State and Actions in React components
    • 2.6 Rendering
    • 2.7 Effect
      • 2.7.1 Effect display
      • 2.7.2 Description
    • 2.8 Note:
    • 2.9 Attached code
  • 3. Example 2 – Small practice example
    • 3.1 Add another Dog component
    • 3.1.1 Writing dogSlice
      • 3.1.2 Modify store.js
      • 3.1.3 Writing dog component
      • 3.1.4 Effect
    • 3.2 This data sharing is too simple, right?
      • 3.2.1 Try data sharing
      • 3.2.2 react-redux + redux data sharing
  • 4. About Payload – payload
  • 5. Project code
    • 5.1 Code directory
    • 5.2 Download project

1 Foreword

1.1 redux and react-redux

  • The previous two articles have already introduced it. If you need it, you can click in and take a look:
    Component communication in React (react18) 04 – Getting started with redux.
    Component communication in React (react18) 05 – redux? react-redux (including data sharing).

1.2 About redux-toolkit

1.2.1 official website

  • https://redux-toolkit.js.org/.
  • https://cn.react-redux.js.org/tutorials/quick-start.

1.2.2 Why use Redux Toolkit?

  • First of all, what does the official website say?
  • Then see that createStore has been deprecated in our code, as follows:

1.3 Install Redux Toolkit

  • The installation command is as follows
    npm install @reduxjs/toolkit
    
    yarn add @reduxjs/toolkit
    
  • If the project has not installed react-redux, you can install both together, but there is no need to install redux separately. react-redux + redux-toolkit replaces react-redux + redux
    npm install @reduxjs/toolkit react-redux
    
    yarn add @reduxjs/toolkit react-redux
    

1.4 Redux Toolkit related API

  • Let’s briefly introduce a few

  • The official website is full, so go to the official website

2. Starting example – official website example

  • For the process, please refer to the official address below:
    https://cn.react-redux.js.org/tutorials/quick-start/.

2.1 Create Redux Store

  • Import configureStore API from Redux Toolkit. We will start by creating an empty Redux store and export it as follows:
    import {<!-- --> configureStore } from '@reduxjs/toolkit';
    
    export default configureStore({<!-- -->
      reducer: {<!-- -->
         
      },
    });
    
  • This will create a Redux store and automatically configure the Redux DevTools extension so that you can inspect the store while developing.

2.2 Provide Redux Store for React

  • Just keep this unchanged as before, as follows:

2.3 Create Redux State Slice

2.3.1 counterSlice.js file

  • Creating a slice requires a string name to identify the slice, an initial state value, and one or more reducer functions that define how to update the state. After creating the slice, we can export the generated Redux action creators and the entire slice reducer function.
  • as follows:

2.3.2 Compare the previous action and reducer

  • The previous action writing method is as follows:
    function incrementOne(){<!-- -->
        type:'INCREMENT_ONE'
    }
    function incrementNumber(number){<!-- -->
        type:'INCREMENT_NUMBER',
        number: number
    }
    export default{<!-- -->incrementOne,incrementNumber}
    
  • The previous reducer writing method is as follows
     function countReducer(state = 0,action){<!-- -->
         switch (action.type) {<!-- -->
             case 'INCREMENT_ONE':
                 return state + 1;
             case 'INCREMENT_NUMBER':
                 return state + action.number;
             default:
                 return state;
         }
     }
     export default{<!-- -->countReducer}
    

2.4 Add Slice Reducers to Store

  • Next, we need to import the reducer function from the counter slice and add it to our store. By defining a field in the reducers parameter, we tell the store to use this slice reducer function to handle all updates to that state.
  • So the final store.js is as follows:

2.5 Using Redux State and Actions in React components

  • Now we can use React Redux hooks to let React components interact with the Redux store. We can use useSelector to read data from the store (not through props), and use useDispatch to dispatch actions.
  • The design within the component is as follows:

2.6 Rendering

  • same code

2.7 Effect

2.7.1 Effect display

  • as follows:

2.7.2 Description

  • Click the [Click me + 1], [Click me -1] and [Addend] buttons:
    The corresponding Redux action will be dispatched to the store;
    The counting slice reducer will see actions update its state;
    The component will see the new state value from the store and re-render itself with the new data.

2.8 Note:

  • as follows:

2.9 Attached code

  • counterSlice.js

    import {<!-- -->createSlice} from '@reduxjs/toolkit'
    
    export const counterSlice = createSlice({<!-- -->
        name: 'myFirstCounterSlice', //This name can be chosen as desired. Logo
        initialState: {<!-- -->
            value: 0, //initial value
        },
        reducers: {<!-- --> // Compared with the previous reducer, it is a function, which contains switch statements based on different action types.
            incrementOne: (state) =>{<!-- --> //The action of adding 1 is generated below, which is equivalent to the original action with only type
                state.value + = 1;
            },
            decrementOne: (state) =>{<!-- --> //The action below generates decrement by 1, which is equivalent to the original action with only type
                state.value -= 1;
            },incrementNumber: (state,action) =>{<!-- --> //Equivalent to an action with more than one parameter: type
                state.value + = action.payload; //payload
            }
        }
    });
    
    // Generate Action creators for each case reducer function
    export const {<!-- -->incrementOne,decrementOne,incrementNumber} = counterSlice.actions;
    
    const countReducer = counterSlice.reducer;
    export default countReducer;
    
  • store.js

    import {<!-- --> configureStore } from '@reduxjs/toolkit';
    import countReducer from './reducerAndAction/counterSlice';
    
    export default configureStore({<!-- -->
      reducer: {<!-- -->
         counterState: countReducer,
      },
    });
    
  • Counter.jsx

    import {<!-- -->useRef} from "react";
    import {<!-- --> useDispatch, useSelector } from 'react-redux'
    import {<!-- -->incrementOne,decrementOne,incrementNumber} from '../redux/reducerAndAction/counterSlice'
    
    
    function Couter(){<!-- -->
        // console.log(props);
        const numberRef = useRef();
    
        const count = useSelector((state)=>state.counterState.value);
        const dispatch = useDispatch();
    
        //add 1
        function addOne(){<!-- -->
            dispatch(incrementOne());
        }
    
        //Dynamic increase
        function addNumber(){<!-- -->
            const stringNumber = numberRef.current.value; //The string is taken directly
            const number = parseInt(stringNumber);
            const addNumberAction = incrementNumber(number); //action with parameters
            dispatch(addNumberAction);
        }
    
        return(
            <div>
                The current value is: {<!-- -->count} <br />
                <button onClick={<!-- -->addOne}>Click me + 1</button> & amp;nbsp; & amp;nbsp;
    
                <button onClick={<!-- -->()=>dispatch(decrementOne())}>Click me-1</button>
    
                <br /><br />
                <input type="number" ref={<!-- -->numberRef} placeholder="Please enter the number to add"/> & amp;nbsp; & amp;nbsp;
                <button onClick={<!-- -->addNumber}>AddNumber</button>
            </div>
        )
    }
    
    export default Couter;
    

3. Example 2 – Small practice example

3.1 Add another Dog component

3.1.1 Writing dogSlice

  • as follows:

3.1.2 Modify store.js

  • as follows:

3.1.3 Writing dog component

  • For the sake of convenience, the addition is simply written. If necessary, you can optimize it yourself, as follows:

3.1.4 Effect

  • as follows:

3.2 This data sharing is too simple

3.2.1 Try data sharing

  • Try accessing it directly, the code is as follows:
  • It really works. This is much simpler than redux + react-redux. The effect is as follows

3.2.2 react-redux + redux data sharing

  • Regarding how to implement data sharing with react-redux + redux data sharing, please read the following article if necessary, as follows:
    Component communication in React (react18) 05 – redux? react-redux (including data sharing).

4. About Payload–load payload

  • Regarding state.value + = action.payload; //payload, here is an example. If you still use the original redux, action can also be written as follows:
  • For another example, you can write the Action creation function of “Add a to-do item” like this:
    var id = 1
    function addTodo(content) {<!-- -->
      return {<!-- -->
        type: 'ADD_TODO',
        payload: {<!-- -->
          id: id + + ,
          content: content, // To-do content
          completed: false // Identification of whether it is completed or not
        }
      }
    }
    
  • This allows us to understand why action.payload is used in this way. For the sake of standardization, no matter what parameters you pass, numbers or objects, they are all action.payload. See It will be better understood after looking at our example above, as follows:

5. Project code

5.1 Code Directory

  • as follows:

5.2 Download project

  • as follows:
    Various ways of react (react18) component communication and various detailed examples (including react-redux + redux-toolkit).