1==App.js========================================
2import React from 'react';
3import PageContextProvider from './PageContextProvider';
4import Header from './Header';
5function App() {
6 return (
7 <div className="App">
8 <PageContextProvider>
9 <Header />
10 </PageContextProvider>
11 </div>
12 );
13}
14export default App;
15
16
17==PageContextProvider.js=========================
18import React, { useState, useEffect, createContext } from 'react';
19export const PageContext = createContext();
20const PageContextProvider = (props) => {
21 const [user, setUser] = useState({
22 'name': 'harry potter'
23 });
24 return (
25 <PageContext.Provider value={{
26 user: user,
27 }}>
28 {props.children}
29 </PageContext.Provider>
30 );
31}
32export default PageContextProvider;
33
34
35==Header.js=====================================
36import React, { useContext } from 'react';
37import { PageContext } from './PageContextProvider';
38const Header = () => {
39 const { user } = useContext(PageContext);
40 return (
41 <div className="header">
42 {user.name}
43 </div>
44 );
45}
46export default Header;
1DEFINITION::::::
2Context provide a way to pass data through the component tree without
3having to pass down manually at every level
4
5HOW TO USE::::::
6DECLARATION:::
7 const MyContext = React.createContext()
8Creating a new Context for each unique piece of data that needs to be available
9throughout your component data
10 const LocaleContext = React.createContext()
11Properties of LocaleContext --------
12 LocaleContext.Provider
13 LocaleContext.Consumer
14
15What is a Provider
16 Allows us to "declare the data that we want available throughout our
17 component tree"
18
19What is a Consumer
20 Allows "any component in the tree that needs that data to be able to
21 subscibe to it"
22
23How to use Provider
24 <MyContext.Provider value={data}>
25 <App />
26 </MyContext.Provider>
27
28
29
30
31