import {useContext} from "react" code example
Example: react usecontext examples
import React from "react";
import ReactDOM from "react-dom";
const NumberContext = React.createContext();
function App() {
return (
<NumberContext.Provider value={42}>
<div>
<Display />
</div>
</NumberContext.Provider>
);
}
function Display() {
return (
<NumberContext.Consumer>
{value => <div>The answer is {value}.</div>}
</NumberContext.Consumer>
);
}
ReactDOM.render(<App />, document.querySelector("#root"));
import React, { useContext } from 'react';
function Display() {
const value = useContext(NumberContext);
return <div>The answer is {value}.</div>;
}