There is a delay state variable controlled by a slider, but its value is not used.
Pass the delay value to your custom useCounter Hook, and change the useCounter Hook to use the passed delay instead of hardcoding 1000 ms.
Here is the code:
//App.js
import { useState } from 'react';
import { useCounter } from './useCounter.js';
export default function Counter() {
const [delay, setDelay] = useState(1000);
const count = useCounter();
return (
<>
<label>
Tick duration: {delay} ms
<br />
<input
type="range"
value={delay}
min="10"
max="2000"
onChange={e => setDelay(Number(e.target.value))}
/>
</label>
<hr />
<h1>Ticks: {count}</h1>
</>
);
}
//useCounter.js
import { useState, useEffect } from 'react';
export function useCounter(delay) {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(c => c + 1);
}, delay);
return () => clearInterval(id);
}, [delay]);
return count;
}
I’ve been trying to make the useCounter
hook respect the delay set by the user in the Counter
component, but it doesn’t work.
2
Answers
I think you forgot to give the useCounter function its variable.
Try passing the
delay
variable to your useCounter function like so:useCounter(delay)
You could move the
delay
into the custom hook, and then return it,count
, and the setters.