Skip to content

Instantly share code, notes, and snippets.

View Jahans3's full-sized avatar
:shipit:

Josh J Jahans3

:shipit:
View GitHub Profile
const StateContent = createContext();
export function useStore () {
const { state, dispatch } = useContext(StateContext);
return [state, dispatch];
}
@Jahans3
Jahans3 / use-reducer.js
Last active December 1, 2018 17:48
Use reducer
export function StateProvider ({ state: initialState, reducers, middleware, children }) {
const [state, dispatch] = useReducer((state, action) => {
return reducers.reduce((state, reducer) => reducer(state, action) || state, state);
}, initialState);
return (
<StateContext.Provider value={{ state, dispatch }}>
{children}
</StateContext.Provider>
);
@Jahans3
Jahans3 / use-state.js
Created December 1, 2018 01:14
Use state
import React, { useState } from 'react';
function Counter () {
const [count, setCount] = useState(0);
return (
<>
<span>
Count: {count}
</span>
<button onClick={() => setCount(count + 1)}>
@Jahans3
Jahans3 / provider-with-middleware.js
Last active December 1, 2018 19:55
Provider with middleware
export class StateProvider extends React.PureComponent {
static defaultProps = {
state: {},
reducers: [],
middleware: []
};
state = this.props.state;
_dispatch = action => {
@Jahans3
Jahans3 / use-middleware.js
Last active December 1, 2018 00:16
Use middleware
export default function Root () {
return (
<StateProvider
state={initialState}
reducers={[countReducer]}
middleware={[countMiddleware]}
>
<MyApp />
</StateProvider>
);
@Jahans3
Jahans3 / count-middleware.js
Last active December 1, 2018 00:15
Count middleware
function countMiddleware ({ type, payload }, { count }) {
if (type === ADD_N) {
console.log(`${payload} + ${count} = ${payload + count}`);
return null;
}
}
@Jahans3
Jahans3 / dispatching-actions.js
Last active December 10, 2018 18:24
Dispatching actions
export default function SomeCount () {
return (
<StateConsumer>
{({ state, dispatch }) => (
<>
<p>
Count: {state.count}
</p>
<button onClick={() => dispatch(addOne())}>
+ 1
@Jahans3
Jahans3 / reducer-provider.js
Created November 30, 2018 03:39
Passing our reducers
export default function Root () {
return (
<StateProvider state={initialState} reducers={[countReducer]}>
<MyApp />
</StateProvider>
);
}
@Jahans3
Jahans3 / count-reducer.js
Last active December 1, 2018 17:43
Count reducer
function countReducer ({ count, ...state }, { type, payload }) {
switch (type) {
case ADD_N:
return { ...state, count: count + payload };
case ADD_ONE:
return { ...state, count: count + 1 };
}
}
@Jahans3
Jahans3 / store-with-dispatch.js
Last active December 1, 2018 17:42
Store with dispatch
export class Provider extends React.PureComponent {
static defaultProps = {
state: {},
reducers: []
};
state = this.props.state;
_dispatch = action => {
const { reducers } = this.props;