Before you get to useContext, you can look at the Context
Context
Context provides a way to pass data between components in a tree without manually adding props for each layer of components. Context is used when many components at different layers need to access the same data. Use caution because this makes components less reusable. So let’s look at the API of the Context
React.createContext
const MyContext = React.createContext(defaultValue);
Copy the code
Note that the defaultValue parameter takes effect only when the component does not match the Provider in the tree. This default is useful for testing components without wrapping them with a Provider. Note: When undefined is passed to the Provider’s value, the consumer component’s defaultValue does not take effect.
Context.Provider
< myContext. Provider value={/* some value */}>Copy the code
The Provider receives a value property and passes it to the consuming component. A Provider can be associated with multiple consumer components. Multiple providers can also be nested, with the inner layer overwriting the data in the outer layer.
When a Provider’s value changes, all of its internal consuming components are rerendered. Both the Provider and its internal consumer component are not subject to the shouldComponentUpdate function, so the consumer component can update if its ancestor exits updating
Class.contextType
class MyClass extends React.Component { static contextType = MyContext; render() { let value = this.context; /* Render work based on this value */}}Copy the code
So simply initialize contextType with a static property, get the context, get the value of the context.
Context.Consumer
< mycontext.consumer > {value => /* Render based on the context value */} </ mycontext.consumer >Copy the code
Find the value provided by the Provider closest to the context above
useContext
Now that you know the Context, how do you use useContext? A quick comparison: before using useContext
import React from 'react';
const NoHookContext = React.createContext(0);
function App(){
return (
<NoHookContext.Provider value={1}>
<getValueView />
</NoHookContext.Provider>
)
}
function getValueView(){
return(
<NoHookContext.Consumer>
{value=><div>{value}</div>}
</NoHookContext.Consumer>
)
}
export default App;
Copy the code
After use:
import React,{useContext} from 'react';
const NoHookContext = React.createContext(0);
function App(){
return (
<NoHookContext.Provider value={1}>
<getValueView/>
</NoHookContext.Provider>
)
}
function getValueView(){
const value = useContext(NoHookContext);
return(
<div>
{value}
</div>
)
}
export default App;
Copy the code
one more things…