useContext hook

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.

  1. To create global function or variable you need to create a folder in Helper Folder

    theme >> src >> _helper

  2. Create two files in Helper folder.One of those files will contain below given code.
  3. import { createContext } from 'react';
    
    const ContactAppContext = createContext();
    
    export default ContactAppContext;
  4. We need to create the Provider in the second file, refer the below code
  5. 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;
  6. After creating the Provider of any context we need to wrap with child components or the component which we are going to use. Refer the below code.
  7. 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.

  8. To understand how to use the useContext variables in components, refer the below code.
  9. import React,{ useContext } from 'react';
    import ContactAppContext from '../../../_helper/Contact/index';
    
    const LeftContact = () => {
      const { users } = useContext(ContactAppContext);
        return(
          <h1>{users}</h1>
        )
    export default LeftContact;