Sobes.tech
Middle+

There is an App component and a Rand component from a third-party library that outputs a random number. How to make the random number change every 3 seconds and display a counter of the number of changes? All in the App component.

sobes.tech AI

Answer from AI

In the App component, you can use state and a timer to update a random number and a change counter every 3 seconds.

Example in React:

import React, { useState, useEffect } from 'react';
import Rand from 'some-rand-library'; // assume Rand exports a function getRandomNumber

function App() {
  const [randomNumber, setRandomNumber] = useState(Rand.getRandomNumber());
  const [count, setCount] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setRandomNumber(Rand.getRandomNumber());
      setCount(prev => prev + 1);
    }, 3000);

    return () => clearInterval(interval);
  }, []);

  return (
    <div>
      <p>Random number: {randomNumber}</p>
      <p>Number of changes: {count}</p>
    </div>
  );
}

export default App;

All the update logic is inside the App component: a useEffect hook creates an interval that updates the state of randomNumber and count every 3 seconds.