gene b.
gene b.

Reputation: 11994

React Router with different paths on same component: does not re-initialize component (useEffect [] not called)

I have a Router defined on different paths using the same component, with the difference indicated via the mode prop.

<Route path="/viewAgreementForm">
    <AgreementForm mode="view" />
</Route>          
<Route path="/editAgreementForm">
    <AgreementForm mode="edit" />
</Route> 

The AgreementForm does some initialization in its useEffect(.., []).

Normally the routing works, but if I go from the View mode directly to the Edit mode, the re-initialization of the Edit-mode component doesn't work. So this section doesn't execute during the button link that takes me from View->Edit, although it does work if I open these routes independently from another screen:

useEffect(() => {
    if (props.mode === 'view') {
        alert('Initializing in View Mode')
    } else {
        alert('NOT initializing in View Mode');
    }
}, []);

Sequence:

  1. Open View mode; correctly get the View initialization
  2. Click the button in the View mode that's supposed to take me to Edit.
  3. I do get the Edit-mode version of the component correctly changed and re-rendered, but I do not get to the initialization of useEffect(.., []), and no alerts at all.

My understanding is: the Router destroys/recreates components on any route, so I'm dealing with brand-new components, isn't that true?

Upvotes: 2

Views: 349

Answers (1)

Amit
Amit

Reputation: 4290

You need to tell useEffect which variables to track, Change to

useEffect(() => {
    if (props.mode === 'view') {
        alert('Initializing in View Mode')
    } else {
        alert('NOT initializing in View Mode');
    }
}, [props.mode]);

(Note added by OP per responder's later comment: When React sees the same component on a new route, it will act as if merely the props have changed, but will not create a brand-new component that would have gone through useEffect(.., []) (initialization.)

Upvotes: 3

Related Questions