useEffect.dev
← Back to lessons

Lesson 2. Trigger side effects with useEffect 7. Exercise & next steps

Update this component so it displays the time elapsed since it was mounted. By updating the input’s value, the user can choose the refresh frequency (in milliseconds) for the displayed time.

Result

There are several ways to accomplish this task. Here is a clue for the one I think is the easiest to implement: you will need three local states:

  • one for the start time (when the component is mounted),
  • one for the refresh frequency (the input’s value),
  • and one the time to display, which should be updated at a given frequency.

Using setInterval, the challenge is to understand when to update the different states. Also, don’t forget to clean up the intervals you create!

Click here to see the solution!
const Exercise = () => {
const [startTime, setStartTime] = useState()
const [refreshEvery, setRefreshEvery] = useState(100)
const [time, setTime] = useState(0)
useEffect(() => {
setStartTime(Date.now())
}, [])
useEffect(() => {
const intervalId = setInterval(() => {
setTime(Date.now() - startTime)
}, refreshEvery)
return () => {
clearInterval(intervalId)
}
}, [refreshEvery, startTime])
return (
<>
<p>
Time: <code>{(time / 1000).toFixed(3)}</code> seconds
</p>
<p>
<label>
Refresh frequency:{' '}
<input
type="number"
value={refreshEvery}
onChange={(event) => setRefreshEvery(Number(event.target.value))}
/>
</label>
</p>
</>
)
}

Next step

Now that we know the two most useful hooks, we can use them together to apply some common patterns and create our hooks.