Search code examples
reactjsreact-hooksreact-statereact-state-management

React state object property calculated from other properties


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.


Solution

  • 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
       }
    });