Skip to content

Instantly share code, notes, and snippets.

@tonkla
Last active July 20, 2019 05:53
Show Gist options
  • Save tonkla/377d6c622064512d9672a0dcac74ab59 to your computer and use it in GitHub Desktop.
Save tonkla/377d6c622064512d9672a0dcac74ab59 to your computer and use it in GitHub Desktop.
React app's global state management with the Context API and Hooks
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 }
@tonkla
Copy link
Author

tonkla commented Jul 20, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment