Search code examples
reactjsreduxreact-reduxreact-hooks

React/Redux : Detect and exectute instructions before component destruction


Ola,

In my redux state, I have a isEditing boolean value, initiate at false, to manage a profile editing mode. I create a redux action to toggle this state. Below, some screen of the component render.

Edit mode off

Edit mode on

It works in most cases:

When I click on Edit name, I toggle to true and display the edit form

When I click on Save (or Cancel), it perform (or not) api request, then toggle to false, displaying the initial component

But if I start editing then quit page manualy (via logo link or url), and then come back to this page, obviously, the edit mode is still active at true.

I would like to put my state to false when I leave page, but I don't find any option to dispatch an action before component destroyed (like old componentWillUnmount() class programming method or beforeUnmount VueJS equivalent)

PS : I use react router V6. It seems a hook was implemented during beta but never released, and no news since :(

An alternative is to force value to false on component creation, with useEffect. It works, but I think it's not the right place. I see the edit mode opened then close in my ui during a few ms.

Thanks in advance


Solution

  • Try using the clean up on an useEffect hook

       useEffect(() => {
        // Specify how to clean up after this effect:
        return function cleanup() {
          // make redux call to toggle edit mode
        };
      });