Created
May 24, 2019 08:26
-
-
Save gre/7c74d760f2ea9cef3273735ecfe3da6b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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