Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Unmount React Functional Component?

I've built several modals as React functional components. They were shown/hidden via an isModalOpen boolean property in the modal's associated Context. This has worked great.

Now, for various reasons, a colleague needs me to refactor this code and instead control the visibility of the modal at one level higher. Here's some sample code:

import React, { useState } from 'react';
import Button from 'react-bootstrap/Button';
import { UsersProvider } from '../../../contexts/UsersContext';
import AddUsers from './AddUsers';

const AddUsersLauncher = () => {
  const [showModal, setShowModal] = useState(false);

  return (
    <div>
      <UsersProvider>
        <Button onClick={() => setShowModal(true)}>Add Users</Button>
        {showModal && <AddUsers />}
      </UsersProvider>
    </div>
  );
};

export default AddUsersLauncher;

This all works great initially. A button is rendered and when that button is pressed then the modal is shown.

The problem lies with how to hide it. Before I was just setting isModalOpen to false in the reducer.

When I had a quick conversation with my colleague earlier today, he said that the code above would work and I wouldn't have to pass anything into AddUsers. I'm thinking though that I need to pass the setShowModal function into the component as it could then be called to hide the modal.

But I'm open to the possibility that I'm not seeing a much simpler way to do this. Might there be?

like image 664
robertwerner_sf Avatar asked Mar 07 '26 20:03

robertwerner_sf


1 Answers

To call something on unmount you can use useEffect. Whatever you return in the useEffect, that will be called on unmount. For example, in your case

const AddUsersLauncher = () => {
  const [showModal, setShowModal] = useState(false);


  useEffect(() => {
    return () => {
      // Your code you want to run on unmount.
    };
  }, []); 


  return (
    <div>
      <UsersProvider>
        <Button onClick={() => setShowModal(true)}>Add Users</Button>
        {showModal && <AddUsers />}
      </UsersProvider>
    </div>
  );
};

Second argument of the useEffect accepts an array, which diff the value of elements to check whether to call useEffect again. Here, I passed empty array [], so, it will call useEffect only once.

If you have passed something else, lets say, showModal in the array, then whenever showModal value will change, useEffect will call, and will call the returned function if specified.

like image 181
McRist Avatar answered Mar 10 '26 16:03

McRist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!