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 >> _helper
import { projectListData } from "Types/projectTypes";
import { Dispatch, SetStateAction, createContext } from "react";
type GlobalType = {
projectData: [] | projectListData[];
setProjectData: Dispatch<SetStateAction<[] | projectListData[]>>;
getAllProjectData: (data:projectListData[]) => void,
};
const ProjectContext = createContext<GlobalType>({
projectData: [],
setProjectData: () => {},
getAllProjectData: () => {},
});
export default ProjectContext;
import { useState } from "react";
import ProjectContext from "./index";
import { projectListData } from "Types/projectTypes";
import { commonContextType } from "Types/CommonElementType";
const ProjectProvider = ({ children }: commonContextType) => {
const [projectData, setProjectData] = useState<[] | projectListData[]>([]);
const getAllProjectData = (data: projectListData[]) => {
setProjectData(data);
};
return (
<ProjectContext.Provider
value={{
projectData,
setProjectData,
getAllProjectData,
}}
>
{children}
</ProjectContext.Provider>
);
};
export { ProjectProvider };
import React from 'react'
import {ProjectContext} from '../ProjectContext'
const App=()=>{
return(
<ProjectContext>
<Routers /> //For Example Children Components
</ProjectContext>
)
}
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 ProjectContext from '../../../_helper/ProjectContext/index';
const LeftContact = () => {
const { projectData } = useContext(ProjectContext);
return(
<h1>{projectData.map((data,index)=>(data.tittle))}</h1>
)
export default LeftContact;