Here we have used “useContext” hook, which creates common data that can be accessed throughout the component hierarchy without passing the props down manually to each level. Context defined will be available to all the child components without involving “props”.
UseContext hook is inbuild hook so we dont need to install any other packages.
Note: In our theme we have created the helper folder, and in that we have added all the context files. It is a good approach and also good way of coding.
theme >> src >> _helper
import { createContext } from 'react';
const ContactAppContext = createContext();
export default ContactAppContext;
import React,{ useState } from 'react';
import Context from './index';
const ContactProvider = (props) => {
const [users, setUsers] = useState([]);
return(
<Context.Provider
value={{
...props,
users,
setUsers
}}>
{props.children}
</Context.Provider>
)
}
export default ContactProvider;
import React from 'react'
import {ContactProvider} from '../ContactProvider'
const App=()=>{
return(
<ContactProvider>
<Routers /> //For Example Children Components
</ContactProvider>
)
}
Info: Instead of <Routers/>
component, here you have to provide child component which has been exported in src > route > router.jsx
file.
import React,{ useContext } from 'react';
import ContactAppContext from '../../../_helper/Contact/index';
const LeftContact = () => {
const { users } = useContext(ContactAppContext);
return(
<h1>{users}</h1>
)
export default LeftContact;