Skip to content

Instantly share code, notes, and snippets.

@r3dm1ke
Last active March 6, 2020 18:11
Show Gist options
  • Save r3dm1ke/2a446f55ebcba83d44492a5a4b12abad to your computer and use it in GitHub Desktop.
Save r3dm1ke/2a446f55ebcba83d44492a5a4b12abad to your computer and use it in GitHub Desktop.
// EXAMPLE WITH CONTEXT + REDUCER
import React, {useContext, useReducer} from 'react';
const AppContext = React.createContext(null);
const ContextProvider = ({children}) => {
const reducer = (state, action) => {
switch (action.type) {
case 'INCREMENT':
return {...state, counter: state.counter + 1};
default:
return state;
}
}
const store = useReducer(reducer, {counter: 0});
return (
<AppContext.Provider value={store}>
{children}
</AppContext>
);
}
const App = () => {
return (
<ContextProvider>
<Counter />
<ContextProvider/>
);
}
const Counter = () => {
const {state, dispatch} = useContext(AppContext);
return (
<>
<button onClick={() => dispatch({type: 'INCREMENT'})}>Click me</button>
<p>You clicked me {state.counter} times</p>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment