Why you need modal state management?
Tags: javascript, react, modal
Published: 2023-06-19 12:47:44

## Why you need modal state management?

Using modals in React is a bit frustrating.

1. If we have a complex modal that contains a large amount of form elements.

2. Or if we have multiple modal components where the next modal component depends on data processed within the previous modal component.

Imagine the issues this could potentially cause.

![Why you need modal state management](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/icq702tywwp7q712lw34.png)


## Problem and Pain Points

When working with modals in React applications, developers often face the following challenges:

1. Modal Logic Coupling: The logic for opening, closing, and managing the state of modals is typically scattered throughout the components that use them. This can make the codebase harder to understand and maintain.

2. Code Organization: Mixing modal logic with other component code can lead to a less organized codebase. Developers may struggle to identify and modify modal-related code when needed.

3. Return Values: When a modal is closed, developers often need to capture the result or user action that occurred within the modal. Managing the return values from modals can be cumbersome and error-prone.

### Problem example

```tsx
function Order() {
    // ...
    const [visible1,setVisible1] = useState(false)
    const [visible2,setVisible2] = useState(false)
    const [visible3,setVisible3] = useState(false)
    
    const withModalState1 = useState<any>()
    const withModalState2 = useState<any>()
    const withModalState3 = useState<any>()

    // ...omit the method inside Modal

    // ...omit other the method inside Component

    return (
        <main>
            ...
            <Modal1 hidden={visible1}></* ... */></Modal1>
            <Modal2 hidden={visible2}></* ... */></Modal3>
            <Modal3 hidden={visible3}></* ... */></Modal3>
        </main>
    ) 
}
```

### Solution example:

```tsx
interface IProps extends InnerModalProps<'ok'/* here is return value's type*/> {
   age: number;
   name: string;
 }

export const InfoModal = EasyModal.create(
 (props: Props) => {
  return (
    <Modal
      title="Hello"
      open={props.visible}
      onOk={() => {
       props.hide('ok'); 
      }}
      onCancel={() => {
      props.hide('cancle'); // ts warn "ok"
      }}
    >
      <h1>{props.age}</h1>
    </Modal>
  );
});

// anywhere use it
EasyModal.show(InfoModal, { name: 'foo' }).then((resolve) => {
  console.log(resolve); // if everything is in order. we will get 'ok' or 'cancle'
});
```



## Why use easy-modal-react ?

[easy-modal-react](https://github.com/raotaohub/ez-modal-react)  is a library for managing modal components' state in React applications.

It provides a solution to decouple the logic of modal components from other components, resulting in more elegant code organization. It is built on the concept of promises and separates the open, close, and other modal states, passing the return values back to the caller through callback resolves after the modal is closed.



Features:

1. Zero Dependency Utility: [easy-modal-react](https://github.com/raotaohub/ez-modal-react) is a standalone utility written in TypeScript that requires no external dependencies.

2. Context-Based State Control: Utilizing context, easy-modal-react efficiently controls modal states throughout your entire application.
3. Promise-Based Handling: Enjoy the benefits of promise-based modal management. 
4. Seamless Component Importing: Effortlessly import modal components throughout your app or use specific component IDs, eliminating the need for explicit imports.
5. Independent Modal Closure: Close modals from within the component itself, independent of the surrounding code. This flexibility allows you to close modals regardless of their location within the application.
6. easy-modal-react can be seamlessly integrated with any UI library that offers similar modal functionality,such as Material UI, Ant Design...


## 🚀 EasyModal Examples

1. **use EasyModal Provider**

```tsx
import EasyModal from 'ez-modal-react';

function App() {/* ... */}

ReactDOM.render(
    <EasyModal.Provider> // wrap your main Componet
      <App />
    </EasyModal.Provider>
  document.getElementById('root'),
);
```

2. **create modal**

```tsx
import easyModal from 'ez-modal-react';

const InfoModal = EazyModal.create((props) => (
  <Modal open={props.visible} onOk={props.hide} onCancel={props.hide}></Modal>
));
```

3. **anywhere use it**

```tsx
import easyModal from 'ez-modal-react';
import InfoModal from './InfoModal';

EasyModal.show(InfoModal, { name: 'foo' }).then((resolve) => {
  console.log(resolve);
});
```
---

## [ez-modal-react-demo - CodeSandbox](https://codesandbox.io/p/sandbox/confident-shape-rt7bzr?embed=1)

click title go to playground-demo.
link:
https://codesandbox.io/p/sandbox/confident-shape-rt7bzr?embed=1

<iframe src="https://codesandbox.io/p/sandbox/confident-shape-rt7bzr?embed=1" width="100%" height="500" scrolling="no" frameborder="no" allowfullscreen="" allowtransparency="true" loading="lazy">
</iframe>

## API Overview

Easy Modal React exposes several key functions and interfaces for working with modals:

### EasyModal.create

The `create` function is used to create a higher-order component (HOC) for a modal. It takes a React component as input and returns a modal component with enhanced functionality.

Example usage:

```tsx
const MyModal = EasyModal.create((props) => {
  // Modal component implementation
    const { hide, remove, resolve, reject, prop1, prop2 } = props
});

// Use MyModal component as a modal in your application
```

### EasyModal.show & EasyModal.hide

The `show` function is used to open a modal. It takes a modal component and optional props as input and returns a promise that resolves with the result when the modal is closed.

Example usage:

```tsx
EasyModal.show(MyModal, { prop1: 'value1', prop2: 'value2' }).then((result) => {
  // Handle the result returned from the modal
});
```

The `hide` function is used to programmatically close a modal. It takes the modal component as input.

Example usage:

```tsx
EasyModal.hide(MyModal);
```

### EasyModal.remove

The `remove` function is used to remove a modal from the modal registry. It takes the modal component as input.

Example usage:

```tsx
EasyModal.remove(MyModal);
```

### useModal Hook

The `useModal` hook is used within a modal component to access modal-related functionality, such as hiding or removing the modal, resolving the promise, or accessing modal-specific props.

Example usage:

```tsx
const MyModal = EasyModal.create(() => {
  const { hide, remove, resolve, reject, prop1, prop2 } = useModal();

  // Use the modal-related functionality and props
});
```

These are the main functions and hooks provided by Easy Modal React to manage modals in your React applications. By using these APIs, you can easily create, show, hide, and remove modals, as well as handle return values and keep your codebase well-organized.

> [learn more](https://github.com/raotaohub/ez-modal-react) 

---

## Conclusion

Because it is open-source, check out this [GitHub repository](https://github.com/raotaohub/ez-modal-react) and feel free to contribute any ideas or feature requests to the project to make it even better!


[easy-modal-react](https://github.com/raotaohub/ez-modal-react) aims to address these pain points by providing a clean and organized way to manage modal components' state and handle return values.


Give [easy-modal-react](https://github.com/raotaohub/ez-modal-react)  a try in your next React