DEV Community

loading...
Cover image for React Clean Code Tricks Everyone Should Know...

React Clean Code Tricks Everyone Should Know...

Sudarshan Sawandkar
賅 瞽
3 min read

TL:DR :

React is unopinionatedly the most famous framework to write the web apps. Due to it's simplistic approach towards handling data and managing state, it is gaining more popularity day by day.

Writing simple todo applications in react not required any deep understanding of the actual code base or the things which are happening under the hood. But, as soon as anyone plans to write the multipage application with react (using several third party libraries) then the individual must have to spend reasonable amount of time on the planning of several things such as :

  • Which state managment library we are going to use
  • Should we go with functional components or class based components
  • How we are splitting our code ?
  • Which bundler to use ? and Many more

So, once this done then actual overhead begins i.e. writing code. This article will help to reduce this overhead and show you some real best practices to handle complex things such as

  • Role base UI Preview
  • Conditional rendering best practices and many more

Role Based UI Rendering :

Almost all application contains basic role based access management system. Handeling each components UI according to the user role is the key factor of every app. By using object literals we can easily manage the UI as follows

image


Use 'Fragments' instead of unnecessary "div's"

When you are wrapping the multiple components in the single

for following the principal of Single Component Return. You are creating multiple s which will be overhead if your applications grows. Hence use fragments instead of divs

    return (
        <>
            <FirstComponentForUser />
            <SecondComponentForUser />
      </> 
    )


Destructure properties earlier :

If the component consumes the data of API (which returns JSON) then we must have to destructure the data earlier. This will prevent us from doing getting things like


        Cannot destructure propertie 'blah' of undefined

For avoiding this do this
image

Here, is one another trick ! I have destructured the properties using the default value which will help us if API return's NULL


Strictly Follow The Import Order

following the import order gives us the clear view about what are our custom imports and what are the built-IN/System imports. This will also helps use to identify any third party imports like axios, moment etc..

image


Write styles in a performant way :

If you have the common styling among the components, then it's better to extract in the styles of section of react. But, even after the applying the common styles if you need to modify something then use rest syntax
image


Use SVG's instead of PNG or JPEG images

Always prefer SVG's (Scaler Vector Graphics) over normal PNG or JPEG images. Reason is, scaling of the SVG is lot more superior than any other relevant image format.
Hence, pixels of image will be rendered sharply regardless of the aspect ratio of the screen.


Final Thoughts :

Best practices always looks ovewhelming when you are just getting started with any technology. But, they will save your time once you start building large scale applications.

Thanks For Reading !

See you in the next One !

Discussion (6)

Collapse
ecyrbe profile image
ecyrbe • Edited

About role management.

What is shown here is a bad practice.

Indeed, in role based systems, roles are not static components. Roles are defined dynamically at runtime by business owners.

They affect rights to roles, create new roles, delete some, update others...

What you as a programmer should rely on is a set of rights the user have.

If a user has the right to edit a content, show him a 'edit' Button, etc...

Do not make giant opaque components that are role based oriented, make small ones that are rights based oriented.

Collapse
sudarshansb143 profile image
Sudarshan Sawandkar Author

Thanks for feedback.

I agree with you on the dynamic nature of the roles.

But, here I focused on the small app which mainly contains two/three types of users

i.e. normal and admin level

Hence, i designed the code in that way !

anyways i will remember your feedback and will take care of it next time :)

Collapse
guruprasaths profile image
guruprasath-s

Hi,
Please help me with some examples code for role based rendering and authorization

Collapse
ecyrbe profile image
ecyrbe

Hello,
If you really are into programming, you should never ask things like that.

Really you should try, test and ask your peers for review. It's the best way to learn.

Nevertheless, here are some suggestions on how to achieve permission based react components.

First never make your basic components permission oriented. Second, try to create either :

  • a custom HOC withRights() that take one or multiples rights to check and a component to return if the rights are ok.
  • a react custom Hook useRights() that take one or multiples rights and return if the connected user is authorised or not.
  • a middleware component 'Rights' that take rights as props and components as childs to render if the connected user as the corresponding rights.

You'll be able to apply it to every business logic that require permissions. For permission based components, i prefer using the component based pattern instead of Hooks or HOC. But all are ok.

This might look like this :

 <Rights allow="list.edit">
   <Button>Edit</Button>
 </Rights>
Enter fullscreen mode Exit fullscreen mode
Collapse
grean profile image
R矇an Guillaume

SVG components are also much smaller than PNG or JPG format, due to their computation at runtime.

Collapse
sudarshansb143 profile image
Sudarshan Sawandkar Author

yup !
and also SVG's are amazingly sharp and good looking on any viewport or any screensize

Forem Open with the Forem app