Quiero crear una aplicación React simple que actualice un elemento h1 cada segundo con la función setInterval. Tengo una matriz con cadenas y cada segundo quiero elegir aleatoriamente una cadena de esa matriz y usar esa cadena dentro de h1. Pero mi código no funciona correctamente. h1 no se actualiza cada segundo sino cada milisegundo.
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 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;Usa el gancho useEffect
Usar reaccionar useEffect
useEffect con dependencia vacía solo se ejecuta en el primer renderizado
intervalo claro en el desmontaje del componente
import PersonalInfo from './PersonalInfo.js' import React, { useState, useEffect } from 'react'; function App() { const myPersonalInfo = ['books', 'music', 'code']; const [state, changeState] = useState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]); useEffect(() => { const intervalId = setInterval(() => { changeState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]); }, 2000); return () => clearInterval(intervalId) }, []) return ( <div className="App"> <PersonalInfo title={state} /> </div> ); } export default App;Use useEffect y establezca el estado como una dependencia.
useEffect(() => { setInterval(() => { changeState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]); }, 2000); }}, [state])