This is the 28th day of my participation in the August Challenge

What is a useReducer?

UseReducer is a way of keeping state for function components and is an alternative to useState. The useReducer allows you to pass dispatches to child components.

What does useReducer accept?

The first argument received is a Reducer function, and the second is an initial state value.

What is returned by the userReducer?

It returns an array, the first element of which is the stored state, and the second element is the dispatch method that starts the action.

What does the defined Reducer function receive and return?

Accepts two parameters, the first is the previous state value, and the second is the Action object

function reducer(state,action) {
    switch (action.type) {
        case 'increment':
            return state + 1
        default:
            returnstate; }}function App(props) {
    
    const [count, dispatch] = useReducer(reducer,0);

    return (
        <div>
            <span>{count}</span>
            <button onClick={()= > dispatch({type: 'increment'})}>+1</button>
        </div>)}Copy the code

What is a useContext?

Simplify code for retrieving data when retrieving data across component hierarchies. The following explains how to use useContext.

  1. Create an xxxContext by createContext().
  2. Wrap through xxxContext.provider and pass the value to the target component.
  3. The target component gets the value passed by value through useContext(xxxContext).
// 1. Create an xxxContext
const countContext = createContext();

// 2. Pass the value to the target component through the xxxContext.Provider package
function App() {
    return (
        <countContext.Provider value={666}>
            <Foo />
        </countContext.Provider>)}// 3. The target component uses useContext(xxxContext) to get the value passed by value
function Foo() {
    const count = useContext(countContext)
    return (
        <div>
            {count}
        </div>)}Copy the code

Note: The argument to useContext must be the context object itself. Components that call useContext are rerendered when the context value changes. The current context value is determined by the <xxxContext.Provider> value prop of the upper-layer component closest to the current component. When a Provider’s value changes, all its internal consumer components are rerendered, and neither the Provider nor its internal consumer components are subject to the shouldComponentUpdate function. The consumer component can also update if its ancestor component exits the update.

reference

  • React createContext and useContext