Have you ever seen a frontend codebase with so many hardcoded values instead of consuming them from the design system theme?
Hardcoded values are a recipe for an inconsistency in the frontend.
Magic numbers should also be avoided when creating responsive layouts.
Frontend Theme
A Frontend Theme defines a standard for colors, typography, size, and spacing in the design system and the product code.
A theme could be represented as a JavaScript object with all these default values.
Fixing the hardcoded values
We are going to use @material/ui and React in the examples, but these apply to any framework or package.
import { createTheme } from '@mui/material/styles';
import { ThemeProvider } from '@mui/styles';
const theme = createTheme();
const Providers = ({ children }) => {
return (
<ThemeProvider theme={theme}>
{children}
</ThemeProvider>
)
}
In the example above we create a theme for our design system based on mui theme, and we added the ThemeProvider
context provider to be able to consume the theme values from everywhere in our codebase.
Here is an example with hardcoded values:
<Typography
variant={'h2'}
sx={{
fontSize: '22px',
color: '#00ff00',
}}
>
{t('Information)}
</Typography>
Without any hardcoded or magic number:
<Typography
variant={'h2'}
sx={{
fontSize: theme.typography.fontSize,
color: theme.typography.color,
}}
>
{t('Information)}
</Typography>
The benefit of the second approach is that you only need to change the fontSize
or text color in one place and it will change everywhere.
You also have more consistency in your UI.
Furthermore, it is easy to add dark mode to your product if you need it.
In Conclusion
Avoiding some antipatterns like hardcoded or magic numbers can increase consistency, reduce maintainability costs, and simplify modifying your design system over time.
You can add a lint rule to throw an error or warning when a developer is trying to commit a hardcoded value to avoid regression.
You can read more about Design Systems at: Every product needs a design system and Practical Guide to Creating a Design System
Woovi
Woovi is a Startup that enables shoppers to pay as they like. Woovi provides instant payment solutions for merchants to accept orders to make this possible.
If you want to work with us, we are hiring!
Top comments (0)