Global State : useReducer and useContext
import React,{createContext,useState,useReducer} from "react";
export const initState={
Name:'sabir',
Contact:'454334',
Roll:'1110',
Count:0
}
export function Student(state,action) {
switch (action.Type) {
case "SetStudent":
return {
Name:action.Name,
Contact:action.Contact,
Roll:action.Roll,
};
case "In":
return {Count:state.Count+1};
case "De":
return {Count:state.Count-1};
}
}
//==========Context API=========
//==========Step1==========
export const StudentContext=createContext();
//=====Step2====
export function StudentDIV({children}){
const [theme,setTheme]=useState('Light');
const [state,dispatch]=useReducer(Student,initState);
return (
<StudentContext.Provider value={{theme,setTheme,state,dispatch}}>
{children}
</StudentContext.Provider>
);
}
===========Use======Index.js====
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {StudentDIV} from "./State/Gstate";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
// <App />
<React.StrictMode>
<StudentDIV>
<App />
</StudentDIV>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
//===========Use in Component
// const [state,dispatch]=useReducer(Student,initState);
const {state,dispatch,setTheme}=useContext(StudentContext);
Comments
Post a Comment