Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!