Introduction In the last post, we have learnt about the brief introduction on Context API and where to use it, its differences from Redux and other third-party plugin that provides central store and also about the components of a Context. In this post, we will see how to write a context object, how to provide it to the components and how to consume it within the components.
Creating a Context object We create a context object using React.createContext(). Below is the snippet.
export const ageContext = React.createContext();
In the snippet, ageContext is the context object that is created. We will create the context Provider, see how the provider acts as the store internally and how the centralized state is passed on to be used in the components.
Creating a Context Provider In this section, we would create a provider for the context object and see how to provide it to the entire component tree.
const state = {
age: 0,
error: null
};
const AgeContextProvider = (props) => {
const [initialState, dispatch] = useReducer(ageReducer, state);
const newAge = initialState.age;
return (
<ageContext.Provider value={{ age: newAge, error:initialState.error, dispatch }}>
{props.children}
</ageContext.Provider>
);
}
export default AgeContextProvider;
In the above snippet, we have created the AgeContextProvider, which is an arrow function that provides an initial state and can be used to dispatch an action as well. For this purpose, we have used a special react hook useReducer[will be discussed in the next post], that replaces the Redux store. As a return value of the function, we are returning the provider attribute of the ageContext object and passing our state and dispatch object as a parameter under value attribute. This ageContext.Provider encloses {props.children}, which means any attribute wrapped inside the AgeContextProvider, would have the state and dispatch provided to it and whenever any component wants to consume it, it can be done in some specific ways. In our example, we would use the AgeContextProvider in the index.js file, which is the root file that wrap the App.js component inside it. So now the context having the state and the dispatch for that state is provided to the entire hierarchical tree structure of the App.js file. Below is the snippet.
ReactDOM.render(
<React.StrictMode>
<AgeContextProvider>
<UserContextProvider>
<App />
</UserContextProvider>
</AgeContextProvider>
</React.StrictMode>,
document.getElementById('root')
);
Consuming a Context There are various ways to consume a context that is provided to the hierarchical tree. Class components and Functional components consume it in different manner. Lets see the different ways to consume a context.
Class Components In Class components, if we want to consume a context object, we need to import the context object and use a static variable in the following syntax -- static contextType = ageContext; This is the nomenclature we should use. Once consumed, we can use is as -- const age = this.context; This age object would have the values that we passed in the ageContext.Provider as shown in the earlier section. This method is used when we use the context object anywhere in the component even outside the render method. When we want to consume multiple context objects, we need to use a separate method and do that inside the render. Below is the syntax. return ( <userContext.Consumer>{(usercontext) => (
<ageContext.Consumer>{(agecontext) => {
return (/*....DOM element...*/)
}}
</ageContext.Consumer>)}
</userContext.Consumer>
); In the above snippet, userContext is another context object just like the ageContext. We need to keep in mind the syntax and the closing of the <userContext.Consumer>. The argument to the arrow function has the entire context object and can be used in the DOM element as required.
Functional Components In case of functional components, we need to use the useContext hook and below is the snippet. const agecontext = useContext(ageContext); const [age, setAge] = useState(agecontext.age); ageContext is the context object and it is stored in the variable agecontext and this object is used to set the state using useState hook. In this case, we can use as many context objects as possible using the useContext hook.
Summary In this post we have seen how to implement a context. It is an alternative of using a store. We have also learnt about its provision and consumption.
Source code -- https://github.com/Titashr/react_app_hooks
댓글