Stop Using Inline Styles in React

Azeem Aleem
2 min readMay 15, 2023

--

Always avoid passing inline Styles to any react components. It's a little tiny thing that causes a huge problem in our React app. To really understand this problem we will review the basic react fundamentals.

Whenever a prop or state changes, react component re-render.

function App(){

return{
<>
<MyComponent style={{height:"10px"}}/>
</>
}
}

If I pass an inline CSS Object in our Component like this. Please notice it's an object {height:”10px”}.

In the fundamentals of Javascript, Objects are not equal to the same object. Let me prove it. If I compare two same objects in the console, it's returning false.

Two same objects are not the same because it's located on different memory addresses.

Using an object literal directly as a style prop in React, such as <MyComponent style={{height:"10px"}}/>, can lead to unnecessary re-renders.

This happens because the object reference changes on each render, causing React's diffing algorithm to consider the style prop as a different value, even if the actual style properties remain the same.

So using Inline CSS in react components cause a little micro re-rendering everywhere in the react application. Because you didn't handle the styles correctly.

So, how we can fix that issue?

Solutions

To avoid this issue, you can use a more stable approach by defining the style object outside of the component render function.

const styles = {
height: "10px"
};

function App() {

return <MyComponent style={styles}> />;
}

By defining the styles object outside the component, it remains the same between renders, ensuring that the style prop won't trigger unnecessary re-renders.

Alternatively, if you need to dynamically change the style based on component state or props, you can use the useMemo hook to memoize the style object. This ensures that the object reference only changes when the dependencies have changed.

import { useMemo } from 'react';

function App({ height }) {

const styles = useMemo(() => ({
height: `${height}px`
}), [height]);

return <MyComponent style={styles} />;
}

In this example, the styles object is memoized using the useMemo hook with the height prop as a dependency. The object will only be recalculated if the height prop changes, preventing unnecessary re-renders.

By using either of these approaches, you can optimize the rendering behavior and ensure that the component doesn’t re-render unnecessarily due to style prop changes.

Follow for more

LinkedIn: https://www.linkedin.com/in/azeemaleem/

Twitter: https://twitter.com/AzeemAleem12

Medium: https://medium.com/@azeemaleem

--

--

Azeem Aleem
Azeem Aleem

No responses yet