-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGlobalState.js
35 lines (29 loc) · 910 Bytes
/
GlobalState.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { useState, createContext, useContext, useEffect } from "react"
// Initial state of this object.
const initialState = {
theme: 'light',
favCount: 0,
locale: 'en',
searchValue: undefined,
filterValue: []
}
// Will be shared across components, through import.
const GlobalContext = createContext(null)
export const GlobalState = (props) => {
const [globalState, setGlobalState] = useState({ ...initialState, ...props })
const updateGlobalState = (key, newValue) => {
setGlobalState(oldState => {
if (oldState[key] !== newValue) {
const newState = { ...oldState }
newState[key] = newValue
return newState
} else {
return oldState
}
})
}
return (
<GlobalContext.Provider value={[globalState, updateGlobalState]}>{props.children}</GlobalContext.Provider>
)
}
export const useGlobalState = () => useContext(GlobalContext)