0

I'm wondering what the best way is to NOT apply styles as one of the results in ternary operator for inline styles, specifically whether its better to pass undefined or {}, as in:

<div style={shouldApplyStyle ? {background: 'black'} : undefined />

OR

<div style={shouldApplyStyle ? {background: 'black'} : {}/>

I know that generally speaking these two function the same, but I'm wondering if passing an empty object would cause unnecessary re-renders because in javascript {} != {} so it would interpret the style prop as having changed every time.

This was pointed out as a possibility in a comment on this answer: https://stackoverflow.com/a/58339902/4440124

In addition to knowing whether passing an empty prop will cause additional rerenders, I'd also like to know if there are any other performance implications or dangers with using one over the other. Thanks!

Marcellus
  • 441
  • 5
  • 16
  • 1
    100% agree with @EmileBergeron, but even if you _have_ determined that this specific component is a performance bottleneck, you'd probably be better off using `useMemo`. But the much more likely scenario is that this is a micro-optimization that isn't worth worrying about. – Lionel Rowe Oct 09 '20 at 22:21
  • @EmileBergeron I asked a similar question but it was closed because the title was opinionated so I made a new one. Again, your comment is irrelevant and unhelpful. This question has nothing to do with when you should optimize an app. I'm not optimizing an app and I'm asking this question mostly of out curiosity. And if I were optimizing an app, if I'd already profiled, I would need to know if I should make this optimization or not. Lastly, with something small like this, its ALWAYS better to do it the optimized way the first time, rather than wait till its an issue and hunt it down then. – Marcellus Oct 09 '20 at 22:24
  • @LionelRowe This is not intended to be a practical question about optimization and avoiding bottlenecks. This is a purely academic (for lack of a better term) question. However, ```useMemo()``` wouldn't work if ```{}``` is interpreted as having changed each time. Since the style prop would be conditional, you would have to tell ```useMemo()``` to check the style prop and since ```{} != {}``` it would re-render each time. This actually could cause performance issues if the component does something intensive on every render because its not expected to re-render often. – Marcellus Oct 09 '20 at 22:35
  • 2
    Fair enough. I guess `useMemo` may not be sufficient if the value changes frequently but often changes back to the same previous value. In that case, another option would be assigning values such as `{}` to constants. `div style={shouldApplyStyle ? OBJECT_WITH_STYLES : EMPTY_OBJECT}`. – Lionel Rowe Oct 09 '20 at 23:05

1 Answers1

2

You are right that passing a new {} style will cause a re-render, especially if its a component. I personally use undefined. undefined === undefined

SILENT
  • 3,916
  • 3
  • 38
  • 57