CodexBloom - Programming Q&A Platform

implementing Class Properties implementation guide in React Component State Management

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
react class-components state-management javascript

I'm building a feature where I tried several approaches but none seem to work... I'm working with a question with class-based components in React where properties are not updating as expected. I have a simple component that maintains a list of items, but when I try to add a new item, it seems like the state isn't being updated correctly. Here's the relevant code: ```javascript import React, { Component } from 'react'; class ItemList extends Component { constructor(props) { super(props); this.state = { items: [] }; } addItem = (item) => { this.state.items.push(item); // This line doesn't trigger a re-render this.setState({ items: this.state.items }); } render() { return ( <div> <ul>{this.state.items.map((item, index) => <li key={index}>{item}</li>)}</ul> <button onClick={() => this.addItem('New Item')}>Add Item</button> </div> ); } } export default ItemList; ``` When I click the 'Add Item' button, I expect the list to update with 'New Item', but it does not. I see that the item is added to the array, but the UI doesn't reflect this change. I tried using `setState` to update the items, but since I directly mutated the `items` array, it doesn't seem to trigger a re-render. If I replace the mutation line with creating a new array, like this: ```javascript this.setState(prevState => ({ items: [...prevState.items, item] })); ``` it works as expected. I understand that directly mutating state should be avoided, but I'm confused about why it behaves like this. Is there a specific reason that state mutations don't lead to a re-render? Is there a best practice I should follow in such scenarios? Any insights would be appreciated! This is for a service running on Windows 11. Am I missing something obvious? This is my first time working with Javascript 3.9. What's the correct way to implement this?