I'm studying useContext
with React Hooks. I would like to pass a single object containing application state to context Consumers, e.g.:
<AppContextProvider.Provider value={AppState}>
{props.children}
</AppContextProvider.Provider>
Of course, I will need to pass some getters
and setters
to enable child components to update application state.
Is this pattern an efficient approach -- is there a better pattern?
const AppContext = React.createContext();
function AppContextProvider(props) {
const AppState = {
aVideoCallIsLive: [get, set] = useState(false),
channelName: [get, set] = useState(null),
localVideoStream: [get, set] = useState(null),
selectedBottomNavIndex: [get, set] = useState(-1),
loginDialogIsOpen: [get, set] = useState(false),
}
}
Why not use a reducer and pass a single dispatch function?
I believe its also recommended you pass state and dispatch is separate contexts otherwise calling dispatch will cause everything inside the context to re render.
https://reactjs.org/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down