Skip to content
Advertisement

React, setInterval not working properly, h1 element not being updated correctly

I want to create a simple React app that upadates a h1 element every second with setInterval function. I have an array with strings and every second I want randomly pick a string from that array and uses that string inside h1. But my code doesn’t work properly. h1 is not being updated every second but every millisecond.

import PersonalInfo from './PersonalInfo.js'
import { useState } from 'react';

function App() {
  const myPersonalInfo = ['books', 'music', 'code']; 
  const [state, changeState] = useState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);

  setInterval(() => {
    changeState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);
  }, 2000);

  return (
    <div className="App">
      <PersonalInfo title={state} />
    </div>
  );
}

export default App;
function PersonalInfo({ title}) {
    return <div>
        <h1>I Love {title} </h1>
    </div>
}

export default PersonalInfo

Advertisement

Answer

    import PersonalInfo from './PersonalInfo.js'
    import { useState } from 'react';
    
    function App() {
      const myPersonalInfo = ['books', 'music', 'code']; 
      const [state, changeState] = useState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);
    
      useEffect(() => {
         setInterval(() => {
            changeState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);
         }, 2000);
      }, [])
    
      return (
        <div className="App">
          <PersonalInfo title={state} />
        </div>
      );
    }
    
    export default App;

Use useEffect hook

Advertisement