Advanced React Patterns

Big Head
  • 👀 View the deployed code on Github.
  • Not happy with the solution? 🐞🐛 Suggest a change.
  • Grammar errors? ✏️ Edit this page.

The State Reducer Pattern

Summary: Create a useAccordion hook that people can easily add their own functionality using the state reducer pattern. Examples of functionality they might want to add is enforcing not having more than one panel at a time or making sure that at least one panel is open at a time or both.

Background

Learn more about The State Reducer Pattern in KCD's blog. This exercise is based on KCD's Simply React talk.

The key here is that hooks can accept a custom reducer function, and users can combine several reducers using a combineReducer function like below

Your module could expose the following to the users:

  1. The useAccordion hook
  2. The default reducer defaultAccordionReducer
  3. The function to create a function that chains the reducers together combineReducer
  4. The action types the reducer can process like togglePanelId
  5. Other reducers to override the defaullts like atleastOnePanelOpenReducer and onlyOnePanelOpenReducer

My solution

FIXME: This accordion implementation does not follow all best accessibility practices. It should be motified according to the specifications, read more at w3.org

The useAccordion hook is just four lines!

You can include more action types, such as a reset actionType if you'd want to.

Here's the default accordion reducer which is just eight lines of code

Here's the reducer that makes sure that atleast one panel is open

Here's the reducer that makes sure that only one panel is open at a time

Here's an example how you can use the hook

And the top level component