Skip to content

Instantly share code, notes, and snippets.

@antoniojps
Last active June 19, 2019 11:52
Show Gist options
  • Select an option

  • Save antoniojps/e2f025753d14410cfde855c0ef1bbdc8 to your computer and use it in GitHub Desktop.

Select an option

Save antoniojps/e2f025753d14410cfde855c0ef1bbdc8 to your computer and use it in GitHub Desktop.
React Hooks and Context for Global State Management Example
import React, { useEffect } from 'react';
import { useExampleContext, actions, ExampleProvider } from 'context/ExampleContext';
const Page = () => {
// first element is the state
// second is the actions dispatcher
const [{ greet }, dispatch] = useExampleContext();
useEffect(() => {
dispatch({
type: actions.GREET_UPDATE,
data: {
greet: 'Hello World',
},
});
}, []);
useEffect(() => {
console.log({ greet })
}, [greet])
return (
<h1>{ greet }</h1>
);
};
export default () => (<ExampleProvider><Page /></ExampleProvider>);
// read https://medium.com/simply/state-management-with-react-hooks-and-context-api-at-10-lines-of-code-baf6be8302c
import React, { createContext, useContext, useReducer } from 'react';
import PropTypes from 'prop-types';
export const ExampleContext = createContext();
// initial state
const initState = {
greet: null,
};
// actions
export const actions = {
GREET_UPDATE: 'GREET_UPDATE',
GREET_REMOVE: 'GREET_REMOVE',
};
// reducer
const reducer = (state, action) => {
const { type, data } = action;
switch (type) {
case actions.GREET_UPDATE:
return {
...state,
greet: data.greet,
};
case actions.GREET_REMOVE:
return {
...state,
greet: null,
};
default:
return state;
}
};
export const ExampleProvider = ({ children }) => (
<ExampleContext.Provider value={useReducer(reducer, initState)}>
{children}
</ExampleContext.Provider>
);
ExampleProvider.propTypes = {
children: PropTypes.node.isRequired,
};
export const useExampleContext = () => useContext(ExampleContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment