0

I'm working on converting an existing codebase to Material UI and am trying to set a standard going forward for how the components are styled.

I've previously worked in a codebase where all the components are styled using the sx prop and didn't notice any particular issues. However, I've seen it recommended in various places that the sx prop should only be used for 'one time' styling and that the styled() API would be a better choice if you need multiple components of the same type to have the same styling.

Although what I don't understand is why that is? If I created a component that was a wrapper around an inner Material UI component and the inner component had been styled with the sx prop. Wouldn't this also achieve the goal of having multiple components of the same type having the same styling? If so, what use is there for the 'styled()' API?

1 Answers1

0

Before sx was added to Material UI styled() was an easy and short syntax to create reuable Material UI components with different styling.

With sx you now can pretty much do everything like styled(), but better.

Some may argue, that requires significant more code to create reuable Material UI components using sx, which is true, but there are two things sx can do and styled() not:

  1. can be conditional based on component state (different style for the component or different styles for different children)
  2. has shorthands / helpers like { ml: 1 } (spacing) or { display: { xl: 'block', xs: 'none' } } (breakpoints)

Especially the last point is a big selling point for sx, because it makes it easier for your styled components be in sync with the MUI styling and theme.

styled() is still a good way to create styled reusable HTMLElements.

Me personally, use sx for everything, but styled reusable HTMLElements.

Joe Scylla
  • 126
  • 5
  • Okay thanks, that's a helpful answer. Are you aware of any performance differences between `styled()` and `sx`? I'd seen some comments around mentioning that `sx` performs worse as it outputs more HTML script tags but I'm not sure how accurate that is. – George Walter Mar 20 '23 at 09:08
  • @GeorgeWalter `sx` is slower than `styled()`. Someone else did some research and benchmarks; see here: https://stackoverflow.com/a/71695686/315363 Based on these benchmarks, in my opinion, the overhead of `sx` is not significant for most use cases. – Joe Scylla Mar 21 '23 at 11:38
  • Is there any advantage to using `sx` over `props` like ` ` – Cathal Mac Donnacha May 19 '23 at 13:07