Why is componentWillUnmount firing after next components componentWillMount? - reactjs

I have a React/Redux application with two components. I need to clear a portion of redux state when the first component unmounts, because the second component will error with the state in that form. I've tried to dispatch an action clearing the chunk of state when the first component unmounts, but the second component begins mounting before the first components componentWillUnmount method is called. When I view dispatched actions in redux-logger, I see the second component dispatching actions from componentWillMount and then componentWillUnmount actions from the previous component called.
This is not the expected behavior is it? I am also using react-router v4. Thanks!

Since React v16, the componentWillUnmount hook can fire asynchronously.
This means that you can't make any assumptions about the order (or timings) of the invocations of these hooks cross-component.

Related

Why don't redux actions "break" componentDidMount/useEffect?

A component will rerender when one of its props changes. That's sort of the whole point of React.
A component that's subscribed to a slice of Redux state will rerender when that state changes. That's sort of the whole point of Redux. And when you use the connect api, those slices of state are simply props, so it goes straight to my first point.
SO, what I'm wondering is:
// only executes once, on mount, right?
componentDidMount() {
this.something()
this.props.someReduxActionThatModifiesAnotherPropInThisComponent()
this.somethingElse()
}
Since the redux action changes the prop, and the component rerenders, I would think that componentDidMount has had its day and now it's done, and we'll never run this.somethingElse().
Obviously I am wrong about this. I know. Can someone tell me what it is that makes this work? What is the whole flow here? I imagine the answer is maybe simply that a component doesn't rerender from inside CDM?
And is it any different in useEffect?
You are correct that componentDidMount only runs once. You are also correct that dispatching a redux action from within the method will trigger a re-render if your component is subscribed.
I think the confusion is about when a re-render occurs.
Updating state only informs React that a re-render is required, it does not pause execution and re-render immediately.
Because of this, the lifecycle method will complete execution of the entire method, and the run the scheduled re-render after.
This is related to why you also cannot use the updated state immediately after calling this.setState (or dispatch in Redux). Because the state is not updated instantly, you've only informed it that an update is required. Behind the scenes, React batches and performs the updates, and then determines what re-renders to perform.
The same is true about Function components and useEffect.
componentDidMount runs only once during the mounting process. But even if you replaced componentDidMount with componentDidUpdate, it also wouldn't rerender before executing the whole function.
The reason to this is that it is actually up to React when to re-render. Sometimes, in situations like yours, React decides not to re-render the component immediately and postpone it.
A similar situation would be when same setState functions are called inside a method. The first setState call doesn't force an immediate re-render.

Why am I getting an infinite loop inside the component as state is globally managed?

I'm working with redux saga and redux toolkit. In the EachUser component, I don't understand why the component is mounting over and over again if I don't use the useEffect hook. Could someone help me understand why it is.
I'm not changing any props or state so I don't think infinite loop should happen but it is happening.
Here is the link to my code sandbox: Redux Saga With Redux toolkit
Happens following:
When you are trying to dispatch your FETCH_SINGLE_USER action on the top level of your functional component it will be executed on each render cycle (your function is re-rendered(executed) each time when props or state changed, also it will be re-rendered when the parent component is re-rendered (if you don't use React.memo).
So when you are dispatching your action on the top level of your functional component it will
fetch user from the server
->
update your store
->
updated store will cause re-render of the component as you are selecting updated state with useSelector
->
fetch user from the server action dispatched again (we are inside of the infinite loop)
So why we need useEffect - it is the hook that helps us to make some actions on special conditions. In the second parameter, you should put an array of dependencies, once dependency changed it will cause hook rerun. If the array is empty - hook will be executed only once when your functional component mounted. Also you can return cleanup function that will be executed, once your component unmounted. More documentation on useEffect hook here
try to remove dispatch from the array of dependencies
useEffect(() => {
dispatch({ type: sagaActions.FETCH_SINGLE_USER, userId });
}, [userId]);
calling a function inside useEffect and specifying it in an array of dependencies can cause an infinite rerender

ComponentWillReceiveProps method does not invoke automatically unless there is some API which triggers this through mapStateToProps function

Suppose I have a React class based component named as "ComponentA". Now I have called the action creator (getCategories) inside componentDidMount hook of this component and get its response inside componentWillReceiveProps through mapStateToProps setting up and carrying state inside redux. Now if I switch to "componentB" and trying to get this already setted up state inside componentWillReceiveProps through mapStateToProps of "ComponentB", the componentWillReceiveProps never invoked unless there is an API call which forcing this to invoke. I want to invoke this method of "ComponentB" everytime I switch to this component without API call. Please let me know the correct solution of this problem. Thanks
As per you description, It is hard to resolve your issue, but this is my try.
As you are switching the component, assuming you click some link, you will never get data in componentWillReceiveProps because whenever you are switching the component, that component only go through below process as a newly mounted component.
componentWillMount() -> Render -> componentDidMount().
This is the process for newly mounted component.
The data you want in componentWillReceiveProps will only come when you pass data from parent to child and not when you switch the component.
As you are using redux, and changing some state in one component (ComponentA), you can access the changed state the another component's (ComponentB) ComponentDidMount().

Will componentWillMount run again if component is re-rendered because of parent component?

Will componentWillMount run again if component is re-rendered because of parent component?
No, componentWillMount is called only once.
Also, componentDidMount is called only once.
componentDidUpdate is called on every re-render.
To correctly understand about the react lifecycle methods you can go through this link.
https://engineering.musefind.com/react-lifecycle-methods-how-and-when-to-use-them-2111a1b692b1
The short answer is NO
It's called once right before your component is about to be rendered to the DOM.
The long answer is:
componentWillMount
Your component is going to appear on the screen very shortly. That chunky render function, with all its beautifully off-putting JSX, is about to be called.
Most Common Use Case: App configuration in your root component.
Can call setState: Yes, but don't. Use the default state instead.
componentDidMount
Here is where you load in your data. ComponentDidMount is also where you can do all the fun things you couldn’t do when there was no component to play with. Basically, here you want to do all the setup you couldn’t do without a DOM, and start getting all the data you need. Most Common Use Case: Starting AJAX calls to load in data for your component.
componentWillReceiveProps
Perhaps some data that was loaded in by a parent component’s componentDidMount finally arrived and is being passed down. Before our component does anything with the new props, componentWillReceiveProps is called, with the next props as the argument.
shouldComponentUpdate
shouldComponentUpdate should always return a boolean — an answer to the question, “should I re-render?” Yes, little component, you should. The default is that it always returns true. It's an awesome place to improve performance.
componentWillUpdate
Most Common Use Case: Used instead of componentWillReceiveProps on a component that also has shouldComponentUpdate (but no access to previous props). It’s basically the same as componentWillReceiveProps, except you are not allowed to call this.setState.
componentDidUpdate
Here we can do the same stuff we did in componentDidMount — reset our masonry layout, redraw our canvas, etc. Basically, we use it when it's all said and done, but we don’t want to waste time to redraw the canvas every time it updates. Most Common Use Case: Updating the DOM in response to prop or state changes.
componentWillUnmount
Here you can cancel any outgoing network requests, or remove all event listeners associated with the component. Basically, clean up anything to do that solely involves the component in question — when it’s gone, it should be completely gone.

redux store dispatch leading to setState error() in React

I'm calling a thunk from a component render function. It works fine if at initial app load the component that calls the thunk loads. however, if I load the app at a different route and then transition to the route which renders the component that calls the thunk , I get the following error:
Warning: setState(...): Cannot update during an existing state
transition (such as within render or another component's
constructor). Render methods should be a pure function of props and
state; constructor side-effects are an anti-pattern, but can be moved
to componentWillMount.
The thunk changes redux store state which is not used by any component in the app and is just used within the thunk via getState() to do some conditional logic. If I remove the dispatch actionCreator code from the thunk the error goes away.
What am i missing?
You just need to keep in mind the basic rule, you should never change your state in the render function of your component. The same rule applies to your component state, as well as to the redux store state. The warning you see on your console is due to the action you are dispatching in your render.
Refactor your code so that all dispatches and state changes take place in other lifecycle methods.

Resources