React component state wiped before component unmounted - reactjs

If I return a function from useEffect I can be sure that that function will run when a component unmounts. But React seems to wipe the local state before it calls my unmounting function.
Consider this:
function Component () {
const [setting, setSetting] = useState(false)
useEffect(() => {
setSetting(true)
// This should be called when unmounting component
return () => {
console.log('Send setting to server before component is unmounted')
console.log(setting) // false (expecting setting to be true)
}
}, [])
return (
<p>Setting is: {setting ? 'true' : 'false'}</p>
)
}
Can anyone confirm that the expected behaviour is that the components state should be wiped? And, if that is the correct behaviour, how does one go about firing off the current component state to a server just before the component is unmounted?
To give some context, I'm debouncing a post request to a server in order to avoid firing it every time the user changes a setting. The debouncing works nicely, but I need a way to fire the request once a user navigates away from the page, as the queued debouncing method will no longer fire from the unmounted component.

It's not that React "wipes out the state value", it's that you have closure on setting value (the value on-mount).
To get expected behavior you should use a ref and another useEffect to keep it up to date.
function Component() {
const [setting, setSetting] = useState(false);
const settingRef = useRef(setting);
// Keep the value up to date
// Use a ref to sync the value with component's life time
useEffect(() => {
settingRef.current = setting;
}, [setting])
// Execute a callback on unmount.
// No closure on state value.
useEffect(() => {
const setting = settingRef.current;
return () => {
console.log(setting);
};
}, []);
return <p>Setting is: {setting ? "true" : "false"}</p>;
}

Related

RXJS subscribe callback doesn't have access to current react state (functional component)

I am using React with functional components in combination with useState() and RxJs.
I'm subscribing to a BehaviorSubject in my useEffect[] and everytime a new message is published, I want to check the current state of my component to decide which steps to take.
But: Even though in my program flow I can clearly see that my state has a certain value, the subscribe callback always only shows the initial empty value. When I stop execution in the middle of the callback, I can see that the "outdated" state is in the closure of the callback.
Why is this?
I've broken it down to those essential code parts:
function DesignView() {
const [name, setName] = useState("");
useEffect(() => {
console.log(name); // <--- This always shows correctly, of course
}, [name]);
useEffect(() => {
// even if this is the ONLY place I use setName() ... it doesn't work
setName("Test Test Test Test");
let subscription = directionService.getDirection().subscribe(() => {
console.log(name); // <--- this only ever shows "" and never "Test Test Test Test"
// no matter at what point of time the published messages arrive!
});
return () => {
subscription.unsubscribe();
}
}, []);
return (
...
);
}
The cause of this problem is that a non-react callback only ever sees a static copy of the state. The same problem appears in the useEffect cleanup function.
Solution:
Either
Add a ref to the state variable. Change the ref.current whenever the state changes and use the ref in the callback
Add the state variable to the dependency array of useEffect and unsubscribe/subscribe every time

Why is the updated state variable not shown in the browser console?

I understand that the method returned by useState is asynchronous, however, when I run the this code, I am delaying the console.log by upto 5 seconds, but it still logs the previous value and not the updated value of the state variable. The updated value would be 2, but it still logs 1. In the react developer tools however, I can see the state changing as I press the button, though I am curious to know why after even such a delay the console prints an obsolete value? This is not the case with class components and setState but with function components and useState.
import "./App.css";
import React, { useState, useEffect } from "react";
function App() {
const [variable, setVariable] = useState(1);
const handleClick = () => {
setVariable(2);
setTimeout(() => {
console.log(variable);
}, 2000);
};
return <button onClick={handleClick}>Button</button>;
}
export default App;
In your code your setTimeout is getting the variable value from the closure at the time it was invoked and the callback function to the setTimeout was created. Check this GitHub issue for the detailed explanation.
In the same issue, they talk about utilizing useRef to do what you are attempting. This article by Dan Abramov packages this into a convenient useInterval hook.
State updates are asynchronous. That means, that in order to view the new value, you need to log It on the next render using useEffect and adding it to the dependencies array:
In this example, give a look at the order the logs appear:
First, you will have the current one, and once triggered, you will have the new value, and then it will become the 'old value' until triggered again.
import "./App.css";
import React, { useState, useEffect } from "react";
function App() {
const [counter, setCounter] = useState(0);
useEffect(() => { console.log(`new state rolled: ${counter}`);
}, [counter]);
console.log(`Before rolling new State value: ${counter}`);
const handleClick = () => setCounter(counter++)
return <button onClick={handleClick}>Button</button>;
}
export default App;
Another technic to console.log a value afterward a state change is to attach a callback to the setState:
setCounter(counter++, ()=> console.log(counter));
I hope it helps.
A state take some time to update. The proper way to log state when it updates, is to use the useEffect hook.
setTimeout attaches the timer and wait for that time, but it will keep the value of variable from the beginning of the timer, witch is 1
import "./App.css";
import React, { useState, useEffect } from "react";
function App() {
const [variable, setVariable] = useState(1);
const handleClick = () => {
setVariable(2);
};
useEffect(() => {
console.log(variable);
}, [variable]);
return <button onClick={handleClick}>Button</button>;
}
export default App;
This is not the case with class components and setState but with
function components and useState
In class components, React keep the state in this.state & then call the Component.render() method whenever its need to update due to a setState or prop change.
Its something like this,
// pseudocode ( Somewhere in React code )
const app = MyClassComponent();
app.render();
// user invoke a callback which trigger a setState,
app.setState(10);
// Then React will replace & call render(),
this.state = 10;
app.render();
Even though you cannot do this.state = 'whatever new value', React does that internally with class components to save the latest state value. Then react can call the render() method and render method will receive the latest state value from this.state
So, if you use a setTimeout in a class component,
setTimeout(() => {
console.log(this.state) // this render the latest value because React replace the value of `this.state` with latest one
}, 2000)
However in functional component, the behaviour is little bit different, Every time when component need to re render, React will call the component again, And you can think the functional components are like the render() method of class components.
// pseudocode ( Somewhere in React code )
// initial render
const app = MyFuctionalComponent();
// state update trigger and need to update. React will call your component again to build the new element tree.
const app2 = MyFunctionalComponent();
The variable value in app is 1 & variable value in app2 is 2.
Note: variable is just a classic variable which returned by a function that hooked to the component ( The value save to the variable is the value return by the hook when the component was rendering so it is not like this.state i.e its hold the value which was there when the component is rendering but not the latest value )
Therefore according to the Clouser, at the time your setTimeout callback invoke ( Which was called from app ) it should log 1.
How you can log the latest value ?
you can use useEffect which getting invoke once a render phase of a component is finished. Since the render phase is completed ( that mean the local state variables holds the new state values ) & variable changed your console log will log the current value.
useEffect(() => {
console.log(variable);
}, [variable])
If you need the behaviour you have in class components, you can try useRef hook. useRef is an object which holds the latest value just like this.state but notice that updating the value of useRef doesn't trigger a state update.
const ref = useRef(0);
const handleClick = () => {
setVariable(2); // still need to setVariable to trigger state update
ref.current = 2 // track the latest state value in ref as well.
setTimeout(() => {
console.log(ref.current); // you will log the latest value
}, 2000);
};

React useState hook always comes as undefined when setting it in useEffect

In my React application, I have a useEffect that checks if an element has the display style none set to it. If it does then it should set the state to false, however it always comes back as undefined.
const [testingProp, setTestingProp] = useState();
useEffect(() => {
const styles = getComputedStyle(customerPropertyTypeSection.current);
if (styles.display == 'none') {
setTestingProp(false);
console.log('style set to none'); // this prints
console.log(testingProp); // this prints 'undefined'
}
}, []);
setState in React acts like an async function.
So putting a console.log(state) right after setting it, will most likely show the former value, which is undefined in this case, as it doesn't actually finish updating the state until the log command runs.
You can use a deticated useEffect hook with the relevant state as a dependency to act upon a change in the state.
Example:
useEffect(() => {
console.log(state);
}, [state]);
Basically, the callback function in the example will run every time the state changes.
P.S. - maybe you can do without the useEffect you are using here to populate the state.
If you have access to customerPropertyTypeSection.current initially, you can do something like this:
const [testingProp, setTestingProp] = useState(() => {
const styles = getComputedStyle(customerPropertyTypeSection.current);
return styles.display !== 'none';
});
If the example above works for you, then the useEffect you are using is redundant and can be removed.

Unexpected behaviour using React useEffect hook

I started studying reaction hooks. But I have some doubts. I thought I understood, but the empirical evidence shows unexpected behavior, at least as far as I believe I know.
To illustrate my perplexities or misunderstandings, I take the classic exercise that implements a simple clock as an example.
Below is the code that implements the functional component.
import {useState, useEffect} from 'react';
const Clock = (props) => {
const {show, country, timezone} = props;
const t = Date.now () + 3600 * timezone * 1000;
const dateInitial = new date (t);
const [datE, setDate] = useState (dateInitial);
useEffect (() => {
const interval = setInterval (() => {
const t = date.getTime () + (1 * 1000);
setDate (new date (t));
}, 1000);
return () => {
// ONLY clears the return of this function
// When the component is unmounted from the DOM
console.log ("Cleanup function (componentWillUnmount ())");
clearTimeout (interval); // The setTimeout is cleared as soon as the component is unmounted from the DOM
}
}, [date);
return (
<h2 style = {{display: show? true: 'none'}}> Today in {country} is {date.toLocaleDateString () + '' + date.toLocaleTimeString ()} </h2>
)
};
export default Clock;
The functional component uses useEffect hooked to the "date" state property.
The function:
() => {
const t = date.getTime () + (1 * 1000);
setDate (new date (t));
}, 1000);
Passed as the first parameter to useEffect, it should be used for componentDidMount and componentDidUpdate life cycle events.
While the cleanup function:
return () => {
// ONLY clears the return of this function
// When the component is unmounted from the DOM
console.log ("Cleanup function (componentWillUnmount ())");
clearTimeout (interval); // The setTimeout is cleared as soon as the component is unmounted from the DOM
}
it should be executed at the componentWillUnmount event of the component lifecycle.
But if I "run" our component, I see this in the logs:
As you can see, the componentWillUnmount event occurred every second. If I'm not wrong, shouldn't the componentWillUnmount happen when the component is removed from the DOM? In this circumstance, we only have a new rendering of the DOM and not the removal of the element from the DOM. I am perplexed. On the other hand, if you try the following example with the class component:
Clock with class component (on codepen.io)
You will see that console.log ("componentWillUnmount"); never appears ...
I also observe that the component that I inserted in the post loses several seconds if I change the tab, while with the one on codepen.io it does not lose a "beat".
Excuse me, I'm a little confused.
I thank you in advance for your always precious clarifications.
useEffect represent componentDidMount and componentWillUnmount only if you give it an empty dependency array:
useEffect(() => {
//code that will only be executed when component mount
return () => {
//code that will only executed when component unmount
}
}, [])
In your example, you have date in the dependency array, this mean, every-time date changes, a new execution, think about it like that useEffect is a mini component which it's life depends on the date value every-time date changes it unmout and remount.
The reason we need the return function in such case, is when we have for example a listener that depend on the date value, so each time the date chnage we need to remove the old listener with old value and attach new listener with new value.
useEffect(() => {
//We attach a listener which depends on date value
const listenerHandler = () => {console.log(date)}
window.addEventListener('event', listenerHandler)
return () => {
//We need to remove the listener with old value so we don't have many listeners attached each time date changes
window.removeEventListener('event', listenerHandler)
}
}, [date])

How to rerender component in useEffect Hook

Ok so:
useEffect(() => {
}, [props.lang]);
What should I do inside useEffect to rerender component every time with props.lang change?
Think of your useEffect as a mix of componentDidMount, componentDidUpdate, and componentWillUnmount, as stated in the React documentation.
To behave like componentDidMount, you would need to set your useEffect like this:
useEffect(() => console.log('mounted'), []);
The first argument is a callback that will be fired based on the second argument, which is an array of values. If any of the values in that second argument change, the callback function you defined inside your useEffect will be fired.
In the example I'm showing, however, I'm passing an empty array as my second argument, and that will never be changed, so the callback function will be called once when the component mounts.
That kind of summarizes useEffect. If instead of an empty value, you have an argument, like in your case:
useEffect(() => {
}, [props.lang]);
That means that every time props.lang changes, your callback function will be called. The useEffect will not rerender your component really, unless you're managing some state inside that callback function that could fire a re-render.
UPDATE:
If you want to fire a re-render, your render function needs to have a state that you are updating in your useEffect.
For example, in here, the render function starts by showing English as the default language and in my use effect I change that language after 3 seconds, so the render is re-rendered and starts showing "spanish".
function App() {
const [lang, setLang] = useState("english");
useEffect(() => {
setTimeout(() => {
setLang("spanish");
}, 3000);
}, []);
return (
<div className="App">
<h1>Lang:</h1>
<p>{lang}</p>
</div>
);
}
Full code:
Simplest way
Add a dummy state you can toggle to always initiate a re-render.
const [rerender, setRerender] = useState(false);
useEffect(()=>{
...
setRerender(!rerender);
}, []);
And this will ensure a re-render, since components always re-render on state change.
You can call setRerender(!rerender) anywhere anytime to initiate re-render.
const [state, set] = useState(0);
useEffect(() => {
fn();
},[state])
function fn() {
setTimeout((), {
set(prev => prev + 1)
}, 3000)
}
The code above will re-render the fn function once every 3 seconds.

Resources