Hooks use useReducer, createContext, useContext to achieve module data sharing, similar to global state management but not recommended for global management

useReducer

Alternative to useState. It accepts a reducer of the form (state, action) => newState, and returns the current state and its dispatch method. (If you're familiar with Redux, you already know how it works.)

Basic use:
const [state, dispatch] = useReducer(reducer, initialArg);

Of course, there is a third parameter, which is not often used and will not be described in detail.
Like other hooks (useState, useEffect, useSelector, useDispatch, etc.), they are all deconstructed from react. When using it, we only need to pass in the action function and the initial state. At this time, useReducer will return us a Array elements, the 0th item of the array is our latest state, and the 1st item is the dispatch function. We only need to pass in our action identifier to change the data in the state and enter react-rudex\redux, which can be achieved automatic render()

action function
const initialState = {
    
    count: 0};

function reducer(state=initialState , action) {
    
    
  switch (action.type) {
    
    
    case 'increment':
      return {
    
    count: state.count + 1};
    case 'decrement':
      return {
    
    count: state.count - 1};
    default:
      throw new Error();
  }
}
use useReducer
function Counter() {
    
    
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {
    
    state.count}
      <button onClick={
    
    () => dispatch({
    
    type: 'decrement'})}>-</button>
      <button onClick={
    
    () => dispatch({
    
    type: 'increment'})}>+</button>
    </>
  );
}

In this way, the state is updated, and we do not use the useState hook. If we want to update a lot of data, we can use a dispatch to solve it, instead of calling multiple setXXXX to update the state. There is also no need to update the state in the parent component in the form of a callback function. useReducer is suitable for a single module. If you want to use useReducer to achieve global state, it is recommended to use the form of creating global state management to solve it.
Hooks use createStore, Provider, useSelector, useDispatch to implement the connect function

In some scenarios, useReducer is more suitable than useState, such as state logic is more complex and contains multiple sub-values, or the next state depends on the previous state, etc. Also, using useReducer can also optimize the performance of components that trigger deep updates, because you can pass dispatch to child components instead of callback functions.

The state of useReducer will also be persistent like the state of useState, and will not change when the component is re-rendered.

createContext && useContext

Using Context we can realize the problem of passing parameters from parent components to grandchild components, whether it is a property or a callback.
You can also cooperate with the above useRecuder to update the state in the state of the parent component by the grandchild component. As long as the grandchild component gets the dispatch in the parent component, it can start the action and make the parent component re-render.

First, we can choose to create a Context in a separate js

export const myName='六卿'
export const myCreateContext= React.createContext();

Introduce this js into the parent component, and use the form of destructuring assignment to get myName and myCreateContext:

import {
    
    myName,myCreateContext} from './xxx.js'

Use in render:

<myCreateContext.Provider value={
    
    myName}>
      <子组件 />
</myCreateContext.Provider>

At this time, we successfully passed myName to the descendant component, whether it is a child component or a grandchild component;
also introduced xxx.js
in the child component or grandchild component, and used the useContext hook in the child component or grandchild component to receive from the parent component. The data;

const myName= useContext(myCreateContext);

At this point we can use the value of myName directly.

useReducer && createContext

Still in the above example, we pass in the value of the value we return in useReducer, state, dispatch

 const [state, dispatch] = useReducer(reducer, initialState);
<myCreateContext.Provider value={
    
    {
    
    state,dispatch}}>
      <子组件 />
</myCreateContext.Provider>

So in the child component or grandchild component we can write like this:

const {
    
    state,dispatch}= useContext(myCreateContext);

This way we can use the state in the parent component, and we can trigger actions in the parent component to change the data in the parent component.
The above operations implement the communication between parent and grandchild components.
The same useReducer and context above are still applicable to a single module, and this form of global data sharing is not recommended.

Other articles

1. Hooks implement toDoList
2. Hooks implement left addition and right subtraction
3. React implements adding a multi-line input box (click a row to add a row)
4. React page jump cancels all requests on the previous page
5. React cooperates with axios request interception verification session, 403 jumps to the login page
6. Hooks use createStore, Provider, useSelector, useDispatch to implement the connect function

Liuqing

见贤思齐焉,见不贤内自省

Personal opinion, please correct me if I am wrong.

Guess you like

Origin blog.csdn.net/qq_43291759/article/details/123508021