Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
how to create a list with stateful components in react?

I'm quite new to react, and I have this problem that when trying to map an array to a list of React stateful component, all my components lose their state. My code:

const { useState, useEffect} = React;

const htmlRoot = document.getElementById('root');
const reactRoot = ReactDOM.createRoot(htmlRoot);

const App = () => {
    const Item = (props) => {
        const [count, setCount] = useState(0);
        useEffect(() => {
            const timer = setInterval(() => {
                setCount((lastCount) => lastCount + 1);
            }, 1000);
            return () => clearInterval(timer);
        }, []);
        return <h1>{props.children + ' ' + count}</h1>;
    };

    const arr = [1, 2, 3];
    const [arrState, setArrState] = useState(arr);
    const clickHandler = () => {
        setArrState((lastArrState) => [
            ...lastArrState,
            lastArrState.at(-1) + 1,
        ]);
    };
    return (
        // Unfortunately, Stack Snippets don't support the shorthand form
        // of fragments
        <React.Fragment>
            {arrState.map((num, index) => (
                <Item key={index}>{num}</Item>
            ))}
            <button onClick={clickHandler}>Click Me</button>
        </React.Fragment>
    );
};

reactRoot.render(<App />);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

Is this even possible for them to keep their state? If it is, how? Update:

almost 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You're creating a new Item component every time your App component is called to render. Since the subsequent renders are using different components that previous renders, React gets rid of the previous instances and creates new ones with fresh state.

Instead, define your Item component outside App and then use it within:

const { useState, useEffect } = React;

const htmlRoot = document.getElementById('root');
const reactRoot = ReactDOM.createRoot(htmlRoot);

const Item = (props) => {
    const [count, setCount] = useState(0);
    useEffect(() => {
        const timer = setInterval(() => {
            setCount((lastCount) => lastCount + 1);
        }, 1000);
        return () => clearInterval(timer);
    }, []);
    return <h1>{props.children + ' ' + count}</h1>;
};

const App = () => {
    const arr = [1, 2, 3];
    const [arrState, setArrState] = useState(arr);
    const clickHandler = () => {
        setArrState((lastArrState) => [
            ...lastArrState,
            lastArrState.at(-1) + 1,
        ]);
    };
    return (
        // (Sadly, Stack Snippets don't support the shorthand form
        // of fragments.)
        <React.Fragment>
            {arrState.map((num, index) => (
                <Item key={index}>{num}</Item>
            ))}
            <button onClick={clickHandler}>Click Me</button>
        </React.Fragment>
    );
};

reactRoot.render(<App />);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>


Separately, don't use index for key (unless the list is static or ever-growing and never reordered — yours fits that latter category, but I'm guessing at some point you'll remove items from it). Details about why in the documentation and the article it links to. Instead, ensure the things being listed have some form of unique, reusable identifier.

almost 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda