Skip to content

Instantly share code, notes, and snippets.

@gre
Created May 24, 2019
Embed
What would you like to do?
/*
* I want to trigger something 5s after mount with some props
*/
const Thing = ({ a, b }) => {
useEffect(() => {
const timeout = setTimeout(() => {
doTheThing(a, b);
}, 5000);
return () => clearTimeout(timeout);
}, []);
return null;
}
// the code above works, the problem is that it's not using the latest value of a and b !
// following code would, but the problem is that my timeout now behaves like a debounce.
const Thing = ({ a, b }) => {
useEffect(() => {
if (theThingIsAlreadyDone()) return;
const timeout = setTimeout(() => {
doTheThing(a, b);
}, 5000);
return () => clearTimeout(timeout);
}, [ a, b ]);
return null;
}
// In previous paradigm i would just use this.props.a and this.props.b and would get the latest value
class Thing extends Component {
componentDidMount() {
this.timeout = setTimeout(() => {
const { a, b } =this.props;
doTheThing(a, b);
}, 5000);
}
componentWillUnmount() {
clearTimeout(this.timeout);
}
render() {
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment