Implements setTimeout()
in a declarative manner.
callback
and a delay
.useRef()
hook to create a ref
for the callback function.useEffect()
hook to remember the latest callback.useEffect()
hook to set up the timeout and clean up.const useTimeout = (callback, delay) => {
const savedCallback = React.useRef();
React.useEffect(() => {
savedCallback.current = callback;
}, [callback]);
React.useEffect(() => {
const tick = () => {
savedCallback.current();
}
if (delay !== null) {
let id = setTimeout(tick, delay);
return () => clearTimeout(id);
}
}, [delay]);
};
const OneSecondTimer = props => {
const [seconds, setSeconds] = React.useState(0);
useTimeout(() => {
setSeconds(seconds + 1);
}, 1000);
return <p>{seconds}</p>;
};
ReactDOM.render(<OneSecondTimer />, document.getElementById('root'));
React, Hooks
Implements fetch()
in a declarative manner.
React, Hooks
Implements setInterval()
in a declarative manner.
React, Hooks
Tracks the browser's location search param.