Will derived state be allowed for React Concurrent Mode?

220 views Asked by At

Today we can use getDerivedStateFromProps for class components and state updates during render phase for React Hooks/function components to create derived state, if needed.

I am especially curious about the React Hook variant: Will this be allowed in React Concurrent Mode?

If I wrap the ScrollView component from the FAQ with StrictMode <React.StrictMode>...</React.StrictMode>, there will be no warnings. However, I still have a slight feeling in stomach, this pattern could be problematic with concurrent mode.

So question is:

Is derived state still possible in React Concurrent Mode with regard to the Hooks FAQ link?


Example:

function Comp( {someCond} ) {
  const [counter, setCounter] = useState(0);

  if (someCond) {
    // we are setting derived state directly in render (see FAQ).
    setCounter(prev => prev + 1);
    // <-- imagine, at this point React aborts this render (and restarts later)
    // Does it lead to inconsistencies?
  }

  // ... return some jsx
}
1

There are 1 answers

1
seyed On

It's safe, but you can only update the state of this component until you have no side-effect on other components during render. in react 16.13.0 a warning added about this.

react 16.13.0 release note:

Warnings for some updates during render A React component should not

cause side effects in other components during rendering.

It is supported to call setState during render, but only for the same component. If you call setState during a render on a different component, you will now see a warning:

Warning: Cannot update a component from inside the function body of a different component.