Home > Net >  Pass props from child to parent without re-rendreing all children
Pass props from child to parent without re-rendreing all children

Time:10-24

I am trying to make a sudoku web app, It consists from a parent component which renders all blocks. Even though every child keeps its own state with the current value inside (all that player could change) I have to update the complete array. It looks something like this

const playerTable = [
  [0, 1, 6, 0, 0, 3, 0, 9, 0],
  [0, 0, 0, 7, 8, 9, 5, 0, 0],
  [7, 9, 0, 0, 0, 6, 3, 2, 4],
  [0, 0, 7, 5, 0, 8, 2, 6, 9],
  [1, 0, 9, 0, 0, 0, 8, 0, 3],
  [0, 8, 2, 0, 3, 7, 0, 0, 0],
  [9, 0, 1, 3, 0, 4, 6, 0, 5],
  [0, 7, 3, 0, 0, 0, 1, 0, 2],
  [4, 6, 5, 0, 2, 1, 9, 0, 7],
]

My idea was to pass the position and new value when state in cube changes and then parent updates the playerTable

playerTable[row][col] = newVal

The problem is all children are re-rendered on any change of state from child to parent, which would be about 36 re-renders.

Is there a way to optimize this or should I leave it like that? Thanks in advance!

CodePudding user response:

Speaking from my knowledge of React...

If your parent component must hold the entire array in its state, whenever that state is updated, all child components will re-render, no matter what. This is a key part of the React diffing algorithm for the virtual DOM.

If you want to make your renders more efficient, then I would say you need to segment and lower your component state, or turn that parent component array state into just data logic that isn't tied to state and re-renders.

Ultimately though, especially with React, I would only bother optimising render cycles if your application is screaming for that optimisation. If your app performs well, then you probably shouldn't waste the time.

  • Related