Skip to content

Instantly share code, notes, and snippets.

@gre
Created May 24, 2019 08:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gre/7c74d760f2ea9cef3273735ecfe3da6b to your computer and use it in GitHub Desktop.
Save gre/7c74d760f2ea9cef3273735ecfe3da6b to your computer and use it in GitHub Desktop.
/*
* 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