Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Discover Mentorship
Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Home/Pills/ Pill - React toggles hook/
Home/Pills/Pill - React toggles hook/
Image by Kelly Sikkema from Unsplash

React toggles hook

Jan 25, 2021

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

React - useToggles.js
  • First, we import the useState hook from React.
  • Then, we createuseToggles hook function which is accepting initialToggles object as a parameter.
  • initialToggles could look like that:
    { isDialogOneOpen: false, isDialogTwoOpen: true }.
  • Then, we use the above object as a default value in the useState hook which returns toggles object and setToggles function to update them.
  • handleToggles function handler is updating the state of the toggles using setToggles function, the name parameter is a string name of the toggle to update, and the value parameter is a boolean.
  • ... spread operator is used to clone existing toggles object and update a boolean value of one concrete toggle by a string name parameter.
  • Lastly, we return toggles and handleToggles as an object from the hook function.

App - 2 dialogs

React - app.js
  • 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 ExampleDialog component to avoid duplication as we use 2 dialogs later on.
  • We use our sweet useToggles hook to control the state of our dialogs.
  • We render Dialog, Button, and Grid components from Material UI mentioned before.
  • toggles and handleToggles are 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 than useState.
  • The point of this pill is to grasp the ability to create custom hooks rather than presenting a concrete solution.
THE GUIDE TO BEAT FRONTEND INTERVIEW
From time to time, I'll send you messages about new blog posts, knowledge pills, and mentoring promotions. Only valuable information, no spam included. You can unsubscribe at any time.
slack
Let's build a community that will help each other.
spread the word
You don't need to, it's okay...