usecontext class component code example
Example 1: reactjs context
==App.js========================================
import React from 'react';
import PageContextProvider from './PageContextProvider';
import Header from './Header';
function App() {
return (
<div className="App">
<PageContextProvider>
<Header />
</PageContextProvider>
</div>
);
}
export default App;
==PageContextProvider.js=========================
import React, { useState, useEffect, createContext } from 'react';
export const PageContext = createContext();
const PageContextProvider = (props) => {
const [user, setUser] = useState({
'name': 'harry potter'
});
return (
<PageContext.Provider value={{
user: user,
}}>
{props.children}
</PageContext.Provider>
);
}
export default PageContextProvider;
==Header.js=====================================
import React, { useContext } from 'react';
import { PageContext } from './PageContextProvider';
const Header = () => {
const { user } = useContext(PageContext);
return (
<div className="header">
{user.name}
</div>
);
}
export default Header;
Example 2: 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>;
}