current position:Home>20 clean code best practices to improve your react project!

20 clean code best practices to improve your react project!

2021-08-27 00:15:38 geeksKai

today , We will discuss some best practices to follow , To improve your React Application health . These rules are widely accepted . therefore , It is necessary to master this knowledge .

1. Use JSX Abbreviation

Use JSX To pass Boolean variables . Suppose you want to control “Navbar” The title visibility of the component .

bad

return (
  <Navbar showTitle={true} />
);
 Copy code 

good

return(
  <Navbar showTitle />  
)
 Copy code 

2. Use ternary operators

Suppose you want to display the details of a specific user by role

bad

const { role } = user;

if(role === ADMIN) {
  return <AdminUser />
}else{
  return <NormalUser />
} 
 Copy code 

good

const { role } = user;

return role === ADMIN ? <AdminUser /> : <NormalUser />
 Copy code 

3. Use object literal

Object literals can help make our code more readable . Suppose you want to display three types of users according to roles . You can't use the ternary system , Because the number of options is greater than two .

bad

const {role} = user

switch(role){
  case ADMIN:
    return <AdminUser />
  case EMPLOYEE:
    return <EmployeeUser />
  case USER:
    return <NormalUser />
}
 Copy code 

good

const {role} = user

const components = {
  ADMIN: AdminUser,
  EMPLOYEE: EmployeeUser,
  USER: NormalUser
};

const Component = components[role];

return <Componenent />;
 Copy code 

4. Use Fragments

Always in Div Upper use Fragment. It keeps the code clean , It also helps to improve performance , Because in virtual DOM The node created in is one less

bad

return (
  <div> <Component1 /> <Component2 /> <Component3 /> </div>  
)
 Copy code 

good

return (
  <>
     <Component1 />
     <Component2 />
     <Component3 />
  </>  
)
 Copy code 

5. Do not define functions inside the rendering

Do not define functions inside the rendering . Try to keep internal logical rendering to an absolute minimum .

bad

return (
    <button onClick={() => dispatch(ACTION_TO_SEND_DATA)}> // NOTICE HERE This is a ### bad example </button>  
)
 Copy code 

good

const submitData = () => dispatch(ACTION_TO_SEND_DATA)

return (
  <button onClick={submitData}>  
    This is a ### good example 
  </button>  
)
 Copy code 

6. Use memo

React.PureComponent and Memo Can significantly improve application performance . They help us avoid unnecessary rendering .

bad

import React, { useState } from "react";

export const TestMemo = () => {
  const [userName, setUserName] = useState("faisal");
  const [count, setCount] = useState(0);
  
  const increment = () => setCount((count) => count + 1);
  
  return (
    <> <ChildrenComponent userName={userName} /> <button onClick={increment}> Increment </button> </>
  );
};

const ChildrenComponent =({ userName }) => {
  console.log("rendered", userName);
  return <div> {userName} </div>;
};
 Copy code 

As far as possible, tube components should be rendered only once , because count The value of is equal to ChildComponent irrelevant . however , It will appear every time you click the button .

good

import React ,{useState} from "react";

const ChildrenComponent = React.memo(({userName}) => {
    console.log('rendered')
    return <div> {userName}</div>
})
 Copy code 

7. take CSS Put in JavaScript in

Writing React Application time , Try to avoid the original JavaScript, Because the organization CSS Ratio organization JS Much more difficult .

bad

// CSS FILE

.body {
  height: 10px;
}

//JSX

return <div className='body'> </div>
 Copy code 

good

const bodyStyle = {
  height: "10px"
}

return <div style={bodyStyle}> </div>
 Copy code 

8. Use object destructors

Using object destructors is good for you . Suppose you need to display user details .

bad

return (
  <> <div> {user.name} </div> <div> {user.age} </div> <div> {user.profession} </div> </>  
)
 Copy code 

good

const { name, age, profession } = user;

return (
  <> <div> {name} </div> <div> {age} </div> <div> {profession} </div> </>  
)
 Copy code 

9.string Type of props There is no need to use flower brackets

The string props When passed to a subcomponent .

bad

return(
  <Navbar title={"My Special App"} />
)
 Copy code 

good

return(
  <Navbar title="My Special App" />  
)
 Copy code 

10. from JSX Delete in JS Code

If anything JS The code is not used for rendering or user interface functions , Then any JS Code from JSX To remove from .

bad

return (
  <ul> {posts.map((post) => ( <li onClick={event => { console.log(event.target, 'clicked!'); // <- THIS IS ### bad }} key={post.id}>{post.title} </li> ))} </ul> );  Copy code 

good

const onClickHandler = (event) => {
   console.log(event.target, 'clicked!'); 
}

return (
  <ul> {posts.map((post) => ( <li onClick={onClickHandler} key={post.id}> {post.title} </li> ))} </ul>
);
 Copy code 

11. Use template text

Use template text to build large strings . Avoid string concatenation . It's good , It's also clean .

bad

const userDetails = user.name + "'s profession is" + user.proffession

return (
  <div> {userDetails} </div>  
)
 Copy code 

good

const userDetails = `${user.name}'s profession is ${user.proffession}`

return (
  <div> {userDetails} </div>  
)
 Copy code 

const userDetails = ${user.name}'s profession is ${user.proffession}

return (

{userDetails}
) ```

12. Orderly import

Always try to import things in a certain order . It improves the readability of the code .

bad

import React from 'react';
import ErrorImg from '../../assets/images/error.png';
import styled from 'styled-components/native';
import colors from '../../styles/colors';
import { PropTypes } from 'prop-types';
 Copy code 

good

The rule of thumb is to keep the import order :

  1. built-in
  2. external
  3. Inside

So the above example becomes :

import React from 'react';

import { PropTypes } from 'prop-types';
import styled from 'styled-components/native';

import ErrorImg from '../../assets/images/error.png';
import colors from '../../styles/colors';
 Copy code 

13. Use implicit return

Use implicit return Of JavaScript Features to write beautiful code . Suppose your function does a simple calculation and returns the result .

bad

const add = (a, b)=>{
  return a + b;
}
 Copy code 

good

const add = (a, b)=> a + b;
 Copy code 

14. Component name

Always use a PascalCase As a component , Use camel for instance Case.

bad

import reservationCard from './ReservationCard';

const ReservationItem = <ReservationCard />;
 Copy code 

good

import ReservationCard from './ReservationCard';

const reservationItem = <ReservationCard />;
 Copy code 

15. Retain props name

Do not use DOM Components props Names are passed between components props, Because others may not expect these names .

bad

<MyComponent style="dark" />

<MyComponent className="dark" />
 Copy code 

good

<MyComponent variant="fancy" />
 Copy code 

16. quotes

JSX Property uses double quotation marks , All the others JS Use single quotes .

bad

<Foo bar='bar' />

<Foo style={{ left: "20px" }} />
 Copy code 

good

<Foo bar="bar" />

<Foo style={{ left: '20px' }} />
 Copy code 

17.props name

If the prop value is React Components , Always use camel's shell as the prop name or PascalCase.

bad

<Component
  UserName="hello"
  phone_number={12345678}
/>
 Copy code 

good

<MyComponent
  userName="hello"
  phoneNumber={12345678}
  Component={SomeComponent}
/>
 Copy code 

18. In brackets JSX

If your component spans multiple lines , Please always wrap it in parentheses .

bad

return <MyComponent variant="long"> <MyChild /> </MyComponent>;
 Copy code 

good

return (
    <MyComponent variant="long"> <MyChild /> </MyComponent>
);
 Copy code 

19. Self closing label

If your component does not have any subcomponents , Please use the self closing label . It improves readability .

bad

<SomeComponent variant="stuff"></SomeComponent>
 Copy code 

good

<SomeComponent variant="stuff" />
 Copy code 

20. Underscore in method name

In any interior React Do not use underscores in methods

bad

const _onClickHandler = () => {
  // do stuff
}
 Copy code 

good

const onClickHandler = () => {
  // do stuff
}
 Copy code 

Last

️ After reading three things :

If you think it's enlightening , I'd like to invite you to do me a little favor :

  1. give the thumbs-up , So that more people can see the content , It is also convenient for you to find this content at any time ( Don't like collection , They're all hooligans -_-);
  2. Pay attention to our , Divide articles irregularly ;
  3. Look at other articles ;

You are welcome to write your learning experience in the message area , Discuss with me and other students . If you feel you have something to gain , Also welcome to share the article with your friends .

copyright notice
author[geeksKai],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827001534822V.html

Random recommended