Last active
July 20, 2019 05:53
-
-
Save tonkla/377d6c622064512d9672a0dcac74ab59 to your computer and use it in GitHub Desktop.
React app's global state management with the Context API and Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createContext, useContext, useCallback, useState } from 'react' | |
const AppContext = createContext({}) | |
const useAppContext = () => { | |
return useContext(AppContext) | |
} | |
const useAppState = () => { | |
const initialState = { count: 0 } | |
const [state, setState] = useState(initialState) | |
const actions = useCallback(getActions(setState), [setState]) | |
return { state, actions } | |
} | |
const getActions = setState => ({ | |
increment: () => { | |
setState(state => ({ ...state, count: state.count + 1 })) | |
}, | |
decrement: () => { | |
setState(state => ({ ...state, count: state.count - 1 })) | |
}, | |
}) | |
export { AppContext, useAppContext, useAppState } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference: https://ricostacruz.com/til/state-management-with-react-hooks