Home > database >  React state object property calculated from other properties
React state object property calculated from other properties

Time:08-07

How could I do something like this:

  const [gameSpecs, setGameSpecs] = useState({
    cols: 10,
    rows: 10,
    numOfCells: cols * rows,
  });

I have read similar questions/answers for objects in vanilla JavaScript but they don't work with React.

CodePudding user response:

You can use the callback initializer of the useState hook:

const [gameSpecs, setGameSpecs] = useState(() => {
   const cols = 10;
   const rows = 10;
   return {
     cols,
     rows,
     numOfCells: cols * rows
   }
});
  • Related