Hacker News new | ask | show | jobs
by tarr11 3225 days ago
React really should be able to detect object literals in style components and optimize those away into a const under the hood. Hopefully this is fixed in a future version.
2 comments

React doesn't do any "compiling". It simply takes the JS object tree that _you_ generated in your component's render function, and works from there. So yes, if you are declaring object literals in your render method, that will be a new object each time the component re-renders.

If you know that a given style object is never going to change, you can hoist it out of your component's render method into the module scope yourself.

This babel preset might do it. I haven't tried but it looks promising...

https://babeljs.io/docs/plugins/transform-react-constant-ele...

I want to say you can 'hint' this by Object.freeze()'ing it.