By WalkingTree   August 12, 2020

React Hooks

Modals are an essential part of building an application. It is a simple and clean way of showing data to the end-user with fewer efforts. Thousands of websites are already using modal extensively. Now how can you implement a modal in your React application? Well, there are many ways to do so. Numerous UI libraries are available which provide an attractive modal interface. 

One of the easiest ways is to create a reusable component by creating a wrapper for these interfaces and use them wherever needed. But, although this method seems easy to implement, it has many problems. Let’s take a look at what the problem is and how React Hooks can help overcome it. 

The Problem

Let’s say you have to add another modal to your application. What will you do? Any developer would simply add another state to open or close the modal, handler to toggle the state on a click, and lastly, add the component (<ModalBase/>). For any modal that you integrate, the same amount of code has to be used, or let’s just call it Code Redundancy. This can get out of control real soon. 

The Solution 

Let’s see how we can fix this issue using React Hooks. Usually, there are 2 types of code in an application – 

  • Dynamic: Content of the modal and other props
  • Static: the process of toggling the modal’s open state

The solution is really simple. You have to isolate both the parts into 2 different codes using hooks. Now, this can be done in 2 parts – 

  • Part 1: Moving the code related to the modal content and its related functionality to its custom hook exposed in the form of a container. Additionally another custom hook to use the modal container to get the context and handle the process of toggling and closing the modal. Finally, a modal component which will make use of both the hooks to handle the complete modal functionality, container for the dynamic part and hook for the static.
  • Part 2: Using Context API to make the modal  accessible throughout the application. 

Read on to know more about modals and how it can be used with React Hooks.


Privacy Preferences
When you visit our website, it may store information through your browser from specific services, usually in form of cookies. Here you can change your privacy preferences. Please note that blocking some types of cookies may impact your experience on our website and the services we offer.