When you're working with React and have multiple instances of the same component, managing state can get tricky. Depending on how your components need to interact, you'll want to handle state differently. Here’s what I’ve found works well.
If your components don’t need to talk to each other, it’s best to keep their state inside the component. This way, each instance has its own state, and changes in one don’t affect the others.
function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } // Usage <Counter /> // Instance 1 <Counter /> // Instance 2
Here, each Counter component keeps track of its own count. So, if you click the button in one counter, it doesn’t change the count in the other.
But if the components need to share some state or work in a coordinated manner, it’s better to move the state up to the parent component. The parent can manage the shared state and pass it down as props. This ensures that all instances stay in sync and work together smoothly.
function Parent() { const [sharedCount, setSharedCount] = useState(0); return ( <div> <p>Total Count: {sharedCount}</p> <Counter count={sharedCount} setCount={setSharedCount} /> <Counter count={sharedCount} setCount={setSharedCount} /> </div> ); } function Counter({ count, setCount }) { return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
This approach works because when the state is in the parent component, any update to that state triggers a re-render of all instances, ensuring they all display the latest UI. If the state were kept in each instance separately, only the instance with the state change would re-render, leading to inconsistent UI across instances.
Examples from My Projects
I figured this out while building an accordion component. Here are two examples from my own work:
Independent Accordion Instances: example. In this setup, each accordion instance works independently.
Dependent Accordion Instances: example. In this version, all accordion instances depend on each other and stay in sync.
Quick Recap
If components work separately, keep state inside each component.
If they need to share state or work together in a coordinated manner, manage the state in the parent.
This approach made a big difference for me when building these accordion examples. Hope it helps you too!
The above is the detailed content of Managing State in Multiple Instances of the Same Component in React. For more information, please follow other related articles on the PHP Chinese website!