Reputation: 11994
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:
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
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