Hook
Let us react to the presence of the hook to stateless components have some new cognition, in particular, it also offers a variety of hooks, such as useReducer useRef, useEffect, useMemo, useCallback, useState, useContext.. .
In development, you’ve probably used Redux, which is a state management container that makes it easy to share data. So can we do state sharing without redux? Perhaps not using third-party libraries (Redux, Mobx, etc.) was a difficult problem to solve before hooks came along. Now the emergence of hook makes it easy for us to solve this problem.
Now let’s implement the state management container of class Redux using useReducer, useContext, and createContext.
Note: the premise is that old friends should know the use of these three Api, do not understand the elder brother to supplement their own brain
State management container based on Hook implementation
First, create a file hookRedux/index.js in the root directory
import React, { createContext, useReducer } from 'react'
export const HookContext = createContext()
function reducer(state = { footer: 'One foot' }, action) {
switch (action.type) {
case 'changeData': return {
...state,
footer: 'Two feet'
}
default: return state
}
}
function HookRedux(props) {
let [data, dispatch] = useReducer(reducer,{ footer: 'One foot' })
return (
<div>
<HookContext.Provider value={{ data, dispatch }}>
{props.children}
</HookContext.Provider>
</div>
)
}
export default HookRedux
Copy the code
Install the HookRedux component on top of the App component, create a component/footer.js file in the root directory, and import it
import React from 'react';
import HookRedux from './hookRedux';
import Footer from './component/footer';
function App() {
return (
<HookRedux>
<div className="App">
<header className="App-header">
<Footer></Footer>
</header>
</div>
</HookRedux>
);
}
export default App;
Copy the code
Third, the Footer component under the HookRedux component can get the data passed down from the HookRedux component
import React, { useContext } from 'react'
import { HookContext } from '.. /hookRedux/index'
function Footer(props) {
let { data, dispatch } = useContext(HookContext)
return (
<div>
<div>{data.footer}</div>
<button onClick={()=>{dispatch({type:'changeData',footer:"Make it two feet."</button> </div>)}export default Footer
Copy the code
In three steps, we can implement a Redux-like state management container, so easy!