UseContext Hook in React.js
Hooks are introduced in React to make the usage of components easy and more manageable. useContext is a built in hook. It provides the functional components easy access to your context. For datas that need to be shared across components global state is very useful. Class based components can work in local state so they were used before hooks came. In a class based component you could build a contextType or a <consumer>. Hooks can manage everything class based components used to, so this hook does nothing new but follows the pattern we used to follow. Lets see the difference of using hooks and the typical way with an example.
import React from "react";import ReactDOM from "react-dom";// Create a Contextconst NumberContext = React.createContext();// It returns an object with 2 values:// { Provider, Consumer }function App() {// Use the Provider to make a value available to all// children and grandchildrenreturn (<NumberContext.Provider value={42}><div><Display /></div></NumberContext.Provider>);}function Display() {// Use the Consumer to grab the value from context// Notice this component didn't get any props!return (<NumberContext.Consumer>{value => <div>The answer is {value}.</div>}</NumberContext.Consumer>);}ReactDOM.render(<App />, document.querySelector("#root"));
In the above standard way we have to wrap out content in a NumberContext.consumer and use render property pattern to get the value inside the component. Now the below example is the context way.
// import useContext (or we could write React.useContext)import React, { useContext } from 'react';// ...function Display() {const value = useContext(NumberContext);return <div>The answer is {value}.</div>;}
Comments
0 comments
Please Sign in or Create an account to Post Comments