SoFunction
Updated on 2025-04-13

Example of React method to update array using setState (append new data)

if (newData) {
  setData((prevData) => [...prevData, ...newData]); // Add new data}

1. Code interpretation

1. Functional Overview

The functions of the above code are:Put new data (newData) Append to the existing data array. By usingsetStateFunction, React will trigger the re-render of the component so that the user interface reflects the latest state.

Core logic:

  • Conditional judgment: Check firstnewDataWhether it exists, ensure that the additional data is valid.
  • Status update:passsetDataUpdate the status and use the callback function to get the current statusprevData, and thennewDataMerge intoprevData, form a new array.

2. Key syntax analysis

Callback function setData((prevData) => ...)

setStateTwo methods are provided:

  • Pass the new status value directly:setState(newState)
  • Use the callback function to calculate the new state value:setState((prevState) => newState)

When state updates depend on previous states, it is recommended to use a callback function because it ensures that the latest state is retrieved and avoids data inconsistencies due to asynchronous behavior.

Extended operator [...prevData, ...newData]

  • [...prevData]: Expand the existing state array into a new array to ensure that the original array is not directly modified (the immutability requirement of React state).
  • [...prevData, ...newData]: Expand the new data array and append it to the end of the original data array to generate a new array.

2. The importance of React state immutability

1. Definition of immutability

In React, states and properties are designed to be immutable. This means that you cannot modify the state directly, but must passsetStateCreate a new state.

Risk of direct modification

The following code directly modifies the status, which is the wrong usage:

(newItem);
setData(data); // ❌ Error: The original state was modified directly

Doing so will result in:

  • React cannot detect changes in states because the state reference has not changed, resulting in the component not being re-rendered.
  • Raise unpredictable errors, especially when using complex data structures.

The correct way to do it

Always create a new state object or array:

setData((prevData) => [...prevData, newItem]);

3. Practical application scenarios of code

1. Load more data

When the page loads, when the user clicks the "Load More" button, he can append the newly acquired data to the existing data list:

const loadMoreData = async () => {
  const newData = await fetchMoreData(); // Simulate to get new data  if (newData) {
    setData((prevData) => [...prevData, ...newData]);
  }
};

2. Real-time update list

In a chat application, when a new message is received, the message can be appended to the end of the message list:

("newMessage", (message) => {
  setMessages((prevMessages) => [...prevMessages, message]);
});

4. Why choose the callback function?

1. Asynchronousness of status updates

React'ssetStateIt is asynchronous. Using the old state value directly can cause overwrite issues when updating the state multiple times.

Error Example

setData([...data, newItem1]); // Suppose at this time data = [1, 2]setData([...data, newItem2]); // It may still be data = [1, 2]

The second call may overwrite the first update because twicesetDataAll use the samedata

Correct example

Use the callback function to ensure that each time you are updated based on the latest state:

setData((prevData) => [...prevData, newItem1]);
setData((prevData) => [...prevData, newItem2]);

2. Support for concurrency mode

In React's concurrency mode (React 18+), status updates may be batched. The callback function ensures that each update is based on the latest state.

5. Performance optimization suggestions

1. Avoid excessive re-rendering

Each status update triggers component re-rendering. If the list is too large, it may cause performance problems.

use

For subcomponents that do not require frequent updates, you can useCache rendering results to reduce unnecessary rendering.

const Item = (({ item }) => <div>{item}</div>);

2. Virtual scrolling

When the list data is very large, you can consider using virtual scrolling (such asreact-windoworreact-virtualized), render only the content of the visual area.

This is the article about React using setState to update arrays (append new data). For more related React setState to update array content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!