The State Reducer Pattern with React Hooks

Photo by Alex Eckermann

A pattern for you to use in custom hooks to enhance the power and flexibility of your hooks.

Some History

A while ago, I developed a new pattern for enhancing your React components called the state reducer pattern. I used it in downshift to enable an awesome API for people who wanted to make changes to how downshift updates state internally.

If you're unfamiliar with downshift, just know that it's an "enhanced input" component that allows you to build things like accessible autocomplete/typeahead/dropdown components. It's important to know that it manages the following items of state: isOpen , selectedItem , highlightedIndex , and inputValue .

Downshift is currently implemented as a render prop component, because at the time, render props was the best way to make a "Headless UI Component" (typically implemented via a "render prop" API) which made it possible for you to share logic without being opinionated about the UI. This is the major reason that downshift is so successful.

Today however, we have React Hooks and hooks are way better at doing this than render props. So I thought I'd give you all an update of how this pattern transfers over to this new API the React team has given us. (Note: Downshift has plans to implement a hook)

As a reminder, the benefit of the state reducer pattern is in the fact that it allows "inversion of control" which is basically a mechanism for the author of the API to allow the user of the API to control how things work internally. For an example-based talk about this, I strongly recommend you give my React Rally 2018 talk a watch:

Read also on my blog: "Inversion of Control"

So in the downshift example, I had made the decision that when an end user selects an item, the isOpen should be set to false (and the menu should be closed). Someone was building a multi-select with downshift and wanted to keep the menu open after the user selects an item in the menu (so they can continue to select more).

By inverting control of state updates with the state reducer pattern, I was able to enable their use case as well as any other use case people could possibly want when they want to change how downshift operates internally. Inversion of control is an enabling computer science principle and the state reducer pattern is an awesome implementation of that idea that translates even better to hooks than it did to regular components.

Using a State Reducer with Hooks

Ok, so the concept goes like this:

End user does an action Dev calls dispatch Hook determines the necessary changes Hook calls dev's code for further changes 👈 this is the inversion of control part Hook makes the state changes

WARNING: Contrived example ahead: To keep things simple, I'm going to use a simple useToggle hook and component as a starting point. It'll feel contrived, but I don't want you to get distracted by a complicated example as I teach you how to use this pattern with hooks. Just know that this pattern works best when it's applied to complex hooks and components (like downshift).

1 function useToggle ( ) { 2 const [ on , setOnState ] = React . useState ( false ) 3 4 const toggle = ( ) => setOnState ( o => ! o ) 5 const setOn = ( ) => setOnState ( true ) 6 const setOff = ( ) => setOnState ( false ) 7 8 return { on , toggle , setOn , setOff } 9 } 10 11 function Toggle ( ) { 12 const { on , toggle , setOn , setOff } = useToggle ( ) 13 14 return ( 15 < div > 16 < button onClick = { setOff } > Switch Off </ button > 17 < button onClick = { setOn } > Switch On </ button > 18 < Switch on = { on } onClick = { toggle } /> 19 </ div > 20 ) 21 } 22 23 function App ( ) { 24 return < Toggle /> 25 } 26 27 ReactDOM . render ( < App /> , document . getElementById ( 'root' ) )

Now, let's say we wanted to adjust the <Toggle /> component so the user couldn't click the <Switch /> more than 4 times in a row unless they click a "Reset" button:

1 function Toggle ( ) { 2 const [ clicksSinceReset , setClicksSinceReset ] = React . useState ( 0 ) 3 const tooManyClicks = clicksSinceReset >= 4 4 5 const { on , toggle , setOn , setOff } = useToggle ( ) 6 7 function handleClick ( ) { 8 toggle ( ) 9 setClicksSinceReset ( count => count + 1 ) 10 } 11 12 return ( 13 < div > 14 < button onClick = { setOff } > Switch Off </ button > 15 < button onClick = { setOn } > Switch On </ button > 16 < Switch on = { on } onClick = { handleClick } /> 17 { tooManyClicks ? ( 18 < button onClick = { ( ) => setClicksSinceReset ( 0 ) } > Reset </ button > 19 ) : null } 20 </ div > 21 ) 22 }

Cool, so an easy solution to this problem would be to add an if statement in the handleClick function and not call toggle if tooManyClicks is true, but let's keep going for the purposes of this example.

How could we change the useToggle hook, to invert control in this situation? Let's think about the API first, then the implementation second. As a user, it'd be cool if I could hook into every state update before it actually happens and modify it, like so:

1 function Toggle ( ) { 2 const [ clicksSinceReset , setClicksSinceReset ] = React . useState ( 0 ) 3 const tooManyClicks = clicksSinceReset >= 4 4 5 const { on , toggle , setOn , setOff } = useToggle ( { 6 modifyStateChange ( currentState , changes ) { 7 if ( tooManyClicks ) { 8 9 return { ... changes , on : currentState . on } 10 } else { 11 12 return changes 13 } 14 } , 15 } ) 16 17 function handleClick ( ) { 18 toggle ( ) 19 setClicksSinceReset ( count => count + 1 ) 20 } 21 22 return ( 23 < div > 24 < button onClick = { setOff } > Switch Off </ button > 25 < button onClick = { setOn } > Switch On </ button > 26 < Switch on = { on } onClick = { handleClick } /> 27 { tooManyClicks ? ( 28 < button onClick = { ( ) => setClicksSinceReset ( 0 ) } > Reset </ button > 29 ) : null } 30 </ div > 31 ) 32 }

So that's great, except it prevents changes from happening when people click the "Switch Off" or "Switch On" buttons, and we only want to prevent the <Switch /> from toggling the state.

Hmmm... What if we change modifyStateChange to be called reducer and it accepts an action as the second argument? Then the action could have a type that determines what type of change is happening, and we could get the changes from the toggleReducer which would be exported by our useToggle hook. We'll just say that the type for clicking the switch is TOGGLE .

1 function Toggle ( ) { 2 const [ clicksSinceReset , setClicksSinceReset ] = React . useState ( 0 ) 3 const tooManyClicks = clicksSinceReset >= 4 4 5 const { on , toggle , setOn , setOff } = useToggle ( { 6 reducer ( currentState , action ) { 7 const changes = toggleReducer ( currentState , action ) 8 if ( tooManyClicks && action . type === 'TOGGLE' ) { 9 10 return { ... changes , on : currentState . on } 11 } else { 12 13 return changes 14 } 15 } , 16 } ) 17 18 function handleClick ( ) { 19 toggle ( ) 20 setClicksSinceReset ( count => count + 1 ) 21 } 22 23 return ( 24 < div > 25 < button onClick = { setOff } > Switch Off </ button > 26 < button onClick = { setOn } > Switch On </ button > 27 < Switch on = { on } onClick = { handleClick } /> 28 { tooManyClicks ? ( 29 < button onClick = { ( ) => setClicksSinceReset ( 0 ) } > Reset </ button > 30 ) : null } 31 </ div > 32 ) 33 }

Nice! This gives us all kinds of control. One last thing, let's not bother with the string 'TOGGLE' for the type. Instead we'll have an object of all the change types that people can reference instead. This'll help avoid typos and improve editor autocompletion (for folks not using TypeScript):

1 function Toggle ( ) { 2 const [ clicksSinceReset , setClicksSinceReset ] = React . useState ( 0 ) 3 const tooManyClicks = clicksSinceReset >= 4 4 5 const { on , toggle , setOn , setOff } = useToggle ( { 6 reducer ( currentState , action ) { 7 const changes = toggleReducer ( currenState , action ) 8 if ( tooManyClicks && action . type === actionTypes . toggle ) { 9 10 return { ... changes , on : currentState . on } 11 } else { 12 13 return changes 14 } 15 } , 16 } ) 17 18 function handleClick ( ) { 19 toggle ( ) 20 setClicksSinceReset ( count => count + 1 ) 21 } 22 23 return ( 24 < div > 25 < button onClick = { setOff } > Switch Off </ button > 26 < button onClick = { setOn } > Switch On </ button > 27 < Switch on = { on } onClick = { handleClick } /> 28 { tooManyClicks ? ( 29 < button onClick = { ( ) => setClicksSinceReset ( 0 ) } > Reset </ button > 30 ) : null } 31 </ div > 32 ) 33 }

Implementing a State Reducer with Hooks

Alright, I'm happy with the API we're exposing here. Let's take a look at how we could implement this with our useToggle hook. In case you forgot, here's the code for that:

1 function useToggle ( ) { 2 const [ on , setOnState ] = React . useState ( false ) 3 4 const toggle = ( ) => setOnState ( o => ! o ) 5 const setOn = ( ) => setOnState ( true ) 6 const setOff = ( ) => setOnState ( false ) 7 8 return { on , toggle , setOn , setOff } 9 }

We could add logic to every one of these helper functions, but I'm just going to skip ahead and tell you that this would be really annoying, even in this simple hook. Instead, we're going to rewrite this from useState to useReducer and that'll make our implementation a LOT easier:

1 function toggleReducer ( state , action ) { 2 switch ( action . type ) { 3 case 'TOGGLE' : { 4 return { on : ! state . on } 5 } 6 case 'ON' : { 7 return { on : true } 8 } 9 case 'OFF' : { 10 return { on : false } 11 } 12 default : { 13 throw new Error ( ` Unhandled type: ${ action . type } ` ) 14 } 15 } 16 } 17 18 function useToggle ( ) { 19 const [ { on } , dispatch ] = React . useReducer ( toggleReducer , { on : false } ) 20 21 const toggle = ( ) => dispatch ( { type : 'TOGGLE' } ) 22 const setOn = ( ) => dispatch ( { type : 'ON' } ) 23 const setOff = ( ) => dispatch ( { type : 'OFF' } ) 24 25 return { on , toggle , setOn , setOff } 26 }

Ok, cool. Really quick, let's add that types property to our useToggle to avoid the strings thing. And we'll export that so users of our hook can reference them:

1 const actionTypes = { 2 toggle : 'TOGGLE' , 3 on : 'ON' , 4 off : 'OFF' , 5 } 6 function toggleReducer ( state , action ) { 7 switch ( action . type ) { 8 case actionTypes . toggle : { 9 return { on : ! state . on } 10 } 11 case actionTypes . on : { 12 return { on : true } 13 } 14 case actionTypes . off : { 15 return { on : false } 16 } 17 default : { 18 throw new Error ( ` Unhandled type: ${ action . type } ` ) 19 } 20 } 21 } 22 23 function useToggle ( ) { 24 const [ { on } , dispatch ] = React . useReducer ( toggleReducer , { on : false } ) 25 26 const toggle = ( ) => dispatch ( { type : actionTypes . toggle } ) 27 const setOn = ( ) => dispatch ( { type : actionTypes . on } ) 28 const setOff = ( ) => dispatch ( { type : actionTypes . off } ) 29 30 return { on , toggle , setOn , setOff } 31 } 32 33 export { useToggle , actionTypes }

Cool, so now, users are going to pass reducer as a configuration object to our useToggle function, so let's accept that:

1 function useToggle ( { reducer } ) { 2 const [ { on } , dispatch ] = React . useReducer ( toggleReducer , { on : false } ) 3 4 const toggle = ( ) => dispatch ( { type : actionTypes . toggle } ) 5 const setOn = ( ) => dispatch ( { type : actionTypes . on } ) 6 const setOff = ( ) => dispatch ( { type : actionTypes . off } ) 7 8 return { on , toggle , setOn , setOff } 9 }

Great, so now that we have the developer's reducer , how do we combine that with our reducer? Well, if we're truly going to invert control for the user of our hook, we don't want to call our own reducer . Instead, let's expose our own reducer and they can use it themselves if they want to, so let's export it, and then we'll use the reducer they give us instead of our own:

1 function useToggle ( { reducer } ) { 2 const [ { on } , dispatch ] = React . useReducer ( reducer , { on : false } ) 3 4 const toggle = ( ) => dispatch ( { type : actionTypes . toggle } ) 5 const setOn = ( ) => dispatch ( { type : actionTypes . on } ) 6 const setOff = ( ) => dispatch ( { type : actionTypes . off } ) 7 8 return { on , toggle , setOn , setOff } 9 } 10 11 export { useToggle , actionTypes , toggleReducer }

Great, but now everyone using our component has to provide a reducer which is not really what we want. We want to enable inversion of control for people who do want control, but for the more common case, they shouldn't have to do anything special, so let's add some defaults:

1 function useToggle ( { reducer = toggleReducer } = { } ) { 2 const [ { on } , dispatch ] = React . useReducer ( reducer , { on : false } ) 3 4 const toggle = ( ) => dispatch ( { type : actionTypes . toggle } ) 5 const setOn = ( ) => dispatch ( { type : actionTypes . on } ) 6 const setOff = ( ) => dispatch ( { type : actionTypes . off } ) 7 8 return { on , toggle , setOn , setOff } 9 } 10 11 export { useToggle , actionTypes , toggleReducer }

Sweet, so now people can use our useToggle hook with their own reducer or they can use it with the built-in one. Either way works just as well.

Conclusion

Here's the final version:

1 import React from 'react' 2 import ReactDOM from 'react-dom' 3 import Switch from './switch' 4 5 const actionTypes = { 6 toggle : 'TOGGLE' , 7 on : 'ON' , 8 off : 'OFF' , 9 } 10 11 function toggleReducer ( state , action ) { 12 switch ( action . type ) { 13 case actionTypes . toggle : { 14 return { on : ! state . on } 15 } 16 case actionTypes . on : { 17 return { on : true } 18 } 19 case actionTypes . off : { 20 return { on : false } 21 } 22 default : { 23 throw new Error ( ` Unhandled type: ${ action . type } ` ) 24 } 25 } 26 } 27 28 function useToggle ( { reducer = toggleReducer } = { } ) { 29 const [ { on } , dispatch ] = React . useReducer ( reducer , { on : false } ) 30 31 const toggle = ( ) => dispatch ( { type : actionTypes . toggle } ) 32 const setOn = ( ) => dispatch ( { type : actionTypes . on } ) 33 const setOff = ( ) => dispatch ( { type : actionTypes . off } ) 34 35 return { on , toggle , setOn , setOff } 36 } 37 38 39 40 function Toggle ( ) { 41 const [ clicksSinceReset , setClicksSinceReset ] = React . useState ( 0 ) 42 const tooManyClicks = clicksSinceReset >= 4 43 44 const { on , toggle , setOn , setOff } = useToggle ( { 45 reducer ( currentState , action ) { 46 const changes = toggleReducer ( currentState , action ) 47 if ( tooManyClicks && action . type === actionTypes . toggle ) { 48 49 return { ... changes , on : currentState . on } 50 } else { 51 52 return changes 53 } 54 } , 55 } ) 56 57 return ( 58 < div > 59 < button onClick = { setOff } > Switch Off </ button > 60 < button onClick = { setOn } > Switch On </ button > 61 < Switch 62 onClick = { ( ) => { 63 toggle ( ) 64 setClicksSinceReset ( count => count + 1 ) 65 } } 66 on = { on } 67 /> 68 { tooManyClicks ? ( 69 < button onClick = { ( ) => setClicksSinceReset ( 0 ) } > Reset </ button > 70 ) : null } 71 </ div > 72 ) 73 } 74 75 function App ( ) { 76 return < Toggle /> 77 } 78 79 ReactDOM . render ( < App /> , document . getElementById ( 'root' ) )

And here it is running in a codesandbox:

Remember, what we've done here is enable users to hook into every state update of our reducer to make changes to it. This makes our hook WAY more flexible, but it also means that the way we update state is now part of the API and if we make changes to how that happens, then it could be a breaking change for users. It's totally worth the trade-off for complex hooks/components, but it's just good to keep that in mind.

I hope you find patterns like this useful. Thanks to useReducer , this pattern just kinda falls out (thank you React!). So give it a try on your codebase!

Good luck!