CheapSteaks CheapSteaks - 1 month ago 18
React JSX Question

Why was mutating style deprecated?

The documentation in 0.13 and 0.14 both warn that mutating style has been deprecated, but don't mention why


Reusing and mutating a style object between renders has been deprecated


What should I do if I want to perform state-dependent animations on an element that css class-based animations can't handle? Clone the object each time?

New to react, help and advice much appreciated

Answer

Looking at the test case/expected error, you are correct and should be cloning the object.

Warning: `div` was passed a style object that has previously been
mutated. Mutating `style` is deprecated. Consider cloning it
beforehand. Check the `render` of `App`. Previous style:
{border: "1px solid black"}. Mutated style:
{border: "1px solid black", position: "absolute"}.

https://github.com/facebook/react/blob/fc96f31fade8043856eb7bc34c56598c4a576110/src/renderers/dom/shared/tests/ReactDOMComponent-test.js#L128

I would guess it's similar to the reasoning for props - it saves you from passing a mutable style object around everywhere and ending up losing a lot of the ease of reasoning that React is really good at helping you with.

The props object is now frozen, so mutating props after creating a component element is no longer supported. In most cases, React.cloneElement should be used instead. This change makes your components easier to reason about and enables the compiler optimizations mentioned above.

Comments