Skip to content

Instantly share code, notes, and snippets.

@nimahkh
Last active July 10, 2020 03:05
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nimahkh/9c008aaf2fd2d1cc83cd98c61e54979a to your computer and use it in GitHub Desktop.
Save nimahkh/9c008aaf2fd2d1cc83cd98c61e54979a to your computer and use it in GitHub Desktop.
reactjs simple context functions to manage states
.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 40vmin;
pointer-events: none;
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.fullWidth{
width:100%;
height:500px
}
.blue{
background-color: #61dafb;
}
.green{
background-color: darkgreen;
}
import React from "react";
import {StateProvider} from "./state"
import './App.css';
import {Button} from "./Button";
const App = () => {
const initialState = {
theme: {primary: 'green'}
};
const reducer = (state, action) => {
switch (action.type) {
case 'changeTheme':
return {
...state,
theme: action.newTheme
};
default:
return state;
}
};
return (
<StateProvider initialState={initialState} reducer={reducer}>
<Button/>
</StateProvider>
);
}
export default App;
import {useStateValue} from './state';
import React from "react";
export const Button = () => {
const [{theme}, dispatch] = useStateValue();
return (
<div className={[theme.primary,'fullWidth'].join(" ")}>
<button
className={theme.primary}
onClick={() => dispatch({
type: 'changeTheme',
newTheme: {primary: theme.primary==="blue"?'green':'blue'}
})}
>
Make me blue!
</button>
</div>
);
}
import React, {createContext, useContext, useReducer} from 'react';
export const StateContext = createContext();
export const StateProvider = ({reducer, initialState, children}) => {
const [state, dispatch]= useReducer();
return(
<StateContext.Provider value={}>
{children}
</StateContext.Provider>
)
};
export const useStateValue = () => useContext(StateContext);
export const useStateDisptach = () => useContext(StateDispatchContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment