DEV Community

Jiawei Li
Jiawei Li

Posted on • Updated on

Ways to Reduce your Front-End Codes

Here, several approaches will be introduced to reduce your front-end code base, especially, for reducing css codes.

Tailwind

tailwindcss provides fast, flexible, reliable css classes. Using tailwind you can save time writing your css codes.

For instance, truncate for:

overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
Enter fullscreen mode Exit fullscreen mode

demo

To optimize css codes in production

css-checker

Wonder how to find your duplicated css codes? There is a automatic tool that can help you scanning all your css & styled-components codes and show similar classes with diffs.

DEMO

  • To Install:
npm install -g css-checker-kit
Enter fullscreen mode Exit fullscreen mode
  • To Run:
css-checker
Enter fullscreen mode Exit fullscreen mode

Using useSWR

  • Link: useSWR

  • useSWR can help you to reduce parsing states between components, just call useSWR in anywhere you wish to use the states.

  • useSWR can also help you to reduce duplicated requests and auto-fetch after users' re-focus.

The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.

  • To use it, it's quite simple:
import useSWR from 'swr'

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher)

  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
diballesteros profile image
Diego (Relatable Code)

As you're mentioning Tailwind its probably almost import to mention their official documentation. tailwindcss.com/docs/optimizing-fo... mentions cssnano or Brotli to further optimize the size of the code sent to the client.

However this all depends on the build steps you already have for prod.

Collapse
 
zhcalvin profile image
Jiawei Li

Thanks for mentioning cssnano and Brotli. They are now mentioned inside the doc above.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

What about styled components?
I find it more useful (maintainability, reusability...) than Tailwind which messes up the html/jsx.

Collapse
 
zhcalvin profile image
Jiawei Li

styled-components is a good approach to struct styling codes. But yet, it's priority is not to reduce the size of code base.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Styles are declarative so there's no way to reduce the code base (even if you add an UI kit, the code will be in this kit and thus will be loaded and interpreted).

It's like pretending to reduce HTML code, it makes a non sense, ehat you will do is to optimise as best as possible and reduce unused code to the minimum.