Description
Do you want to request a feature or report a bug?
Feature request? This is more to kickstart a discussion.
What is the current behavior?
With the current proposal, with any promise-based function call, useEffect
must be used something like so
function MyComponent(props) {
const [state, setState] = useState(0);
let unmounted = false;
useEffect(() => {
myXhrRequest()
.then(data => {
if (!unmounted) {
setState(data);
}
});
return () => {
unmounted = true;
};
});
...
}
This is a fairly awkward pattern for promises, as one needs to add an extra check for mounted state potentially quite divorced from the unmount logic. It should be noted that for subscription-based patterns like with rxjs this is fine, but for promises this stinks and is a bit confusing - this would also get repetitive if there are multiple requests involved.
Ideally the useEffect
should make it easier to clean up asynchronous code without imposing on the pattern a user would to carry out async behavior. One manner that could remove the need for the confusing return function is to provide a isMounted
helper function as an argument for the function passed into useEffect that returns whether the current component is mounted. It does not solve the verbosity completely, which might be outside the scope of React, but it removes the need for extra boilerplate that arguably hurts the readability.
With this proposal, the useEffect
part could be rewritten like this
useEffect(({ isMounted }) => {
myXhrRequest()
.then(data => {
if (isMounted()) {
setState(data);
}
});
});
Just some thoughts anyhow, I would understand if this proposal is rejected.