How to render a list of data points with changing props in React?

Viewed 49

I need to visualise a list of data points where each data point has a field to update its value. After all data point values are adjusted, I would would like to get a list of all values.

My problem is here: when I update one value, all data points are rerendered. And if I have a lot of data points, it is getting slow.

From what I understand, there are 2 approaches how to solve the problem:

  1. Store local state at each data point. But then how can I propagate it to the parent component to aggregate it?

  2. Prevent rerendering of data points that were not changed. Should I use useMemo in this case? What is the correct approach?

Here there is the code:

import React from 'react'
import _ from 'lodash'

const numDataPoints = 3
const dataPointsIndices = _.range(0, numDataPoints).map(id => id.toString())
const initDataPointValues = dataPointsIndices.reduce(
  (acc, id) => ({ ...acc, [id]: '' }),
  {}
)

const DataPoints = () => {
  const [dataPointValues, setDataPointValues] =
    React.useState(initDataPointValues)

  const updateDataValue = (id, { value }) => {
    setDataPointValues({
      ...dataPointValues,
      [id]: value,
    })
  }

  return (
    <div>
      <button onClick={() => console.log(dataPointValues)}>
        Log all values
      </button>
      <div>
        {dataPointsIndices.map(id => (
          <DataPoint
            key={id}
            id={id}
            value={dataPointValues[id]}
            updateDataValue={updateDataValue}
          />
        ))}
      </div>
    </div>
  )
}

const DataPoint = ({ id, value, updateDataValue }) => {
  console.log('RENDER DATA POINT:', id, value)
  return (
    <div>
      {`data point: ${id}`}
      <textarea
        value={value}
        onChange={event => {
          const newValue = event.target.value
          updateDataValue(id, { value: newValue })
        }}
      />
    </div>
  )
}

export default DataPoints
0 Answers
Related