Image by Kelly Sikkema from Unsplash
DESCRIPTION
Having too many dialogs, modals, popups in one component and state starts to become repetitive? Solution - write a custom hook for it.
Introduction
I'll use a bunch of Material UI components for preview example but
useToggles hook works with any dialog/modal/popup component as it's just an encapsulated, reusable React state code.Preview
useToggles hook
- First, we import the useState hook from React.
- Then, we create
useToggleshook function which is acceptinginitialTogglesobject as a parameter. initialTogglescould look like that:{ isDialogOneOpen: false, isDialogTwoOpen: true }.- Then, we use the above object as a default value in the
useStatehook which returnstogglesobject andsetTogglesfunction to update them. handleTogglesfunction handler is updating the state of thetogglesusingsetTogglesfunction, thenameparameter is a string name of the toggle to update, and thevalueparameter is a boolean....spread operator is used to clone existingtogglesobject and update a booleanvalueof one concrete toggle by a stringnameparameter.- Lastly, we return
togglesandhandleTogglesas an object from the hook function.
App - 2 dialogs
- Our app code looks a bit intimidating but mostly it's just a boilerplate code for rendering purposes. 😅
- First, we import all the necessary pieces.
- Then, we create
ExampleDialogcomponent to avoid duplication as we use 2 dialogs later on. - We use our sweet
useToggleshook to control the state of our dialogs. togglesandhandleTogglesare used in the above components to handle dialogs state.
Summary
- Extracting repetitive logic is a perfect use case for hooks in React.
- The above solution should work with any library and any dialog/modal/popup components as it's just a React state with extracted logic.
- To make it more scalable and include additional actions, e.g.
toggleAll, useReducer hook would be a more appropriate solution thanuseState. - The point of this pill is to grasp the ability to create custom hooks rather than presenting a concrete solution.
