Skip to content

Instantly share code, notes, and snippets.

@nagappankv
Created January 27, 2023 15:15
Show Gist options
  • Save nagappankv/f4f89ea7fa00244ff1cfb9f754676dc6 to your computer and use it in GitHub Desktop.
Save nagappankv/f4f89ea7fa00244ff1cfb9f754676dc6 to your computer and use it in GitHub Desktop.
Global State Management - Pari
/**
* you can use the GlobalStateContext in any component to access the state and setter functions, and wrap your entire app with the GlobalStateProvider to make the context available throughout your app.
*/
import { GlobalStateProvider } from './globalState';
function App() {
return (
<GlobalStateProvider>
<SearchField />
<GoogleMap />
</GlobalStateProvider>
);
}
import React, { createContext, useState } from 'react';
// create the context
const GlobalStateContext = createContext();
// create the provider
const GlobalStateProvider = ({ children }) => {
const [searchTerm, setSearchTerm] = useState('');
const [mapCenter, setMapCenter] = useState({ lat: 0, lng: 0 });
return (
<GlobalStateContext.Provider value={{ searchTerm, setSearchTerm, mapCenter, setMapCenter }}>
{children}
</GlobalStateContext.Provider>
);
};
// export the context and provider
export { GlobalStateContext, GlobalStateProvider };
/**
* In the SearchField component you can use useContext to access the searchTerm state and setSearchTerm setter function.
In the GoogleMap component you can use useContext to access the mapCenter state and setMapCenter setter function.
*/
import { GlobalStateContext } from './globalState';
function SearchField() {
const { searchTerm, setSearchTerm } = useContext(GlobalStateContext);
return (
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
);
}
function GoogleMap() {
const { mapCenter, setMapCenter } = useContext(GlobalStateContext);
return (
<div>
<GoogleMapReact
center={mapCenter}
onChange={(center) => setMapCenter(center)}
/>
</div>
);
}
/**
* This way the SearchField component can update the searchTerm state, and the GoogleMap component can access and update the mapCenter state, making it possible for the two components to share state and communicate with each other.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment