The Future of React Reducers and Global State Management

What can we expect in the next iteration of React state management tools?

The useReducer Hook

Reducers with Hooks vs Reducers with State Management Packages

export const reducer = (state, action) => {  switch (action.type) {
case 'reset':
return initialState;
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
return state;
}
}
export default reducer
...
import { reducer } from '../reducers/count';
const state = {
count: 0
};
function Counter({initialCount}) { const [state, dispatch] = useReducer(reducer, {count: initialCount}); return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'reset'})}>
Reset
</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
);
}
const [state, dispatch] = useReducer(
reducer,
initialState,
{type: 'reset', payload: initialCount}
);
case 'reset':
return {count: action.payload};

Hooks with Global State

Example package: ReactN

import { useGlobal } from 'reactn';
[ value, setValue ] = useGlobal(key);
[ global, setGlobal ] = useGlobal();//orthis.global

ReactN Re-renders locally

Using Reducers with ReactN

Method 1: Using addReducer

import { addReducer } from 'reactn';
import { reducer } from '../reducers/reducer.js';
function Counter() { const [count, setCount] = useGlobal('count');
addReducer('reducer', reducer);
return (
<>
Count: {this.global.count}
<button onClick={() =>
this.global.reducer({type: 'increment'})}
>+</button>
</>
);
}

Method 2: Using useGlobal

...function Counter() {   const [count, setCount] = useGlobal('count');   const incrementCount = useGlobal(state => ({
count: state.count + 1
}));
return (
<button
onClick={() => { incrementCount() }}>Increment</button>
);
}

Conclusion

Programmer and Author. Director @ JKRBInvestments.com. Creator of LearnChineseGrammar.com for iOS and Android.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store