The correct posture to use createContext
React Uses the Context API in classes and hooks. Before using the Context API, we also need to know why ❓ is used
The reason for introducing the Context
Considering that components can be layered, if a large number of… Props data is confused.
How to use context
- The first step is to introduce the built-in React Context API 📦
- Then create a
provider
- Finally create
consumer
Hook can be used without creatingconsumer
Using createContext
// context.jsx
import React,{createContext,useState} from 'react'
export const demoContext = createContext({})
export const {Provider,Consumer } = demoContext;
const Context = () = >{
const [name,setName] = useState('Mr.long');
const handleNameClick = (params) = > setName(params);
const initValue ={
name,
handleNameClick
}
return <Provider value={initValue}>{props.children}</Provider>
}
export default Context
Copy the code
Using the Consumer component
Consumer is exported from the return value of the createContext function. It is a Render Props mode component.
// Render Name component
import React from 'react'
export default Render class extends React.Component{
render(){
return <div>
<p>{props.name}</p>
<button onClick ={()= >props.handleNameClick(props.name +'! ')}> Click change name</button>
</div>}}// app.jsx
import {Context,Consumer} from './Context'
import React from 'react'
import RenderName from './renderName'
const App = () = >{
return <Context>
<Consumer>
{(value) =><RenderName {. value} / >}
</Consumer>
</Context>
}
Copy the code
useContext
If you want to use a Context in a hook, you can use it with useContext. Look at the code.
import React,{useContext} from 'react'
import {demoContext} from './context'
const HookContext =() = >{
// useContext passes in the instance of createContext instead of the component in it
// contextValue gets the value, the Consumer component is no longer required
const contextValue = useContext(demoContext)
return (
<div>
{contextValue.name}
<button onClick={()= >contextValue.handleNameClick(contextValue.name +'! ')}> Click to change the value</button>
</div>
);
}
export default HookContext
Copy the code
conclusion
Using Context avoids the problem of nested layers of components. But when it uses consumer to fetch values, there’s an extra layer of components. But thanks to useContexthook we can do without the Consumer component. You get the value directly. It’s intuitive. General usage scenarios, such as the global class prefix, or internationalization, Ui theme colors, etc.
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.