Today, we’ll discuss some best practices you can follow to improve your React application health. These rules are widely accepted. Therefore, it is necessary to master this knowledge.
1. Use the JSX abbreviation
Use JSX to pass Boolean variables. Suppose you want to control the visibility of the title of a “Navbar” component.
bad
return (
<Navbar showTitle={true} />
);
Copy the code
good
return(
<Navbar showTitle />
)
Copy the code
2. Use ternary operators
Suppose you want to display the details of a particular user based on roles
bad
const { role } = user;
if(role === ADMIN) {
return <AdminUser />
}else{
return <NormalUser />
}
Copy the code
good
const { role } = user;
return role === ADMIN ? <AdminUser /> : <NormalUser />
Copy the code
3. Use object literals
Object literals help make our code more readable. Suppose you want to display three types of users based on roles. You can’t use ternary because there are more than two options.
bad
const {role} = user
switch(role){
case ADMIN:
return <AdminUser />
case EMPLOYEE:
return <EmployeeUser />
case USER:
return <NormalUser />
}
Copy the code
good
const {role} = user
const components = {
ADMIN: AdminUser,
EMPLOYEE: EmployeeUser,
USER: NormalUser
};
const Component = components[role];
return <Componenent />;
Copy the code
4. Use Fragments could
Always use fragments on divs. It keeps the code clean and also improves performance because one less node is created in the virtual DOM
bad
return (
<div>
<Component1 />
<Component2 />
<Component3 />
</div>
)
Copy the code
good
return (
<>
<Component1 />
<Component2 />
<Component3 />
</>
)
Copy the code
5. Do not define functions inside the render
Do not define functions inside the render. Try to keep internal logic rendering to an absolute minimum.
bad
return (
<button onClick={()= > dispatch(ACTION_TO_SEND_DATA)}> // NOTICE HERE
This is a ### bad example
</button>
)
Copy the code
good
const submitData = () => dispatch(ACTION_TO_SEND_DATA) return ( <button onClick={submitData}> This is a ### good example </button> )Copy the code
6. Use the 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 the code
Although child components should only be rendered once, because the value of count has nothing to do with ChildComponent. However, it is rendered each time you click the button.
good
import React ,{useState} from "react";
const ChildrenComponent = React.memo(({userName}) = > {
console.log('rendered')
return <div> {userName}</div>
})
Copy the code
7. Put CSS in JavaScript
When writing React applications, avoid raw JavaScript because organizing CSS is much more difficult than organizing JS.
bad
// CSS FILE
.body {
height: 10px;
}
//JSX
return <div className='body'>
</div>
Copy the code
good
const bodyStyle = {
height: "10px"
}
return <div style={bodyStyle}>
</div>
Copy the code
8. Use object destructor
Using object destructor works to your advantage. Suppose you want to display user details.
bad
return (
<>
<div> {user.name} </div>
<div> {user.age} </div>
<div> {user.profession} </div>
</>
)
Copy the code
good
const { name, age, profession } = user;
return (
<>
<div> {name} </div>
<div> {age} </div>
<div> {profession} </div>
</>
)
Copy the code
9. Braces are not required for props of string type
When passing the string props to the child component.
bad
return(
<Navbar title={"My Special App} "/ >
)
Copy the code
good
return(
<Navbar title="My Special App" />
)
Copy the code
10. Remove JS code from JSX
Remove any JS code from JSX if it is not used for rendering or user interface functionality.
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 the 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 the code
11. Use template text
Use template literals to build large strings. Avoid string concatenation. It’s nice and clean.
bad
const userDetails = user.name + "'s profession is" + user.proffession
return (
<div> {userDetails} </div>
)
Copy the code
good
const userDetails = `${user.name}'s profession is ${user.proffession}`
return (
<div> {userDetails} </div>
)
Copy the code
const userDetails = ${user.name}'s profession is ${user.proffession}
return (
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 the code
good
The rule of thumb is to keep the import order:
- built-in
- external
- internal
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 the code
13. Use implicit return
Use the JavaScript feature of implicit return to write beautiful code. Suppose your function does a simple calculation and returns the result.
bad
const add = (a, b) = >{
return a + b;
}
Copy the code
good
const add = (a, b) = > a + b;
Copy the code
14. Component naming
Always use PascalCase as the component and camel Case for the instance.
bad
import reservationCard from './ReservationCard';
const ReservationItem = <ReservationCard />;
Copy the code
good
import ReservationCard from './ReservationCard';
const reservationItem = <ReservationCard />;
Copy the code
15. Keep the props name
Do not use the DOM component props names to pass props between components, because others may not expect these names.
bad
<MyComponent style="dark" />
<MyComponent className="dark" />
Copy the code
good
<MyComponent variant="fancy" />
Copy the code
16. The quotation marks
JSX attributes use double quotes, and all other JS use single quotes.
bad
<Foo bar='bar' />
<Foo style={{ left: "20px}} "/ >
Copy the code
good
<Foo bar="bar" />
<Foo style={{ left: '20px' }} />
Copy the code
17. Props
If the item value is the React component, always use the camel shell as the item name or PascalCase.
bad
<Component
UserName="hello"
phone_number={12345678} / >Copy the code
good
<MyComponent
userName="hello"
phoneNumber={12345678}
Component={SomeComponent}
/>
Copy the code
JSX in parentheses
If your component spans multiple lines, always wrap it in parentheses.
bad
return <MyComponent variant="long">
<MyChild />
</MyComponent>;
Copy the code
good
return (
<MyComponent variant="long">
<MyChild />
</MyComponent>
);
Copy the code
19. Autistic labels
If your component does not have any child components, use the closed label. It improves readability.
bad
<SomeComponent variant="stuff"></SomeComponent>
Copy the code
good
<SomeComponent variant="stuff" />
Copy the code
20. Underscores in method names
Do not use underscores in any internal React methods
bad
const _onClickHandler = () = > {
// do stuff
}
Copy the code
good
const onClickHandler = () = > {
// do stuff
}
Copy the code
The last
❤️ Three things to watch:
If you find this article inspiring, I’d like to ask you to do me a small favor:
- Like, so that more people can see this content, but also convenient to find their own content at any time (collection is not like, are playing rogue -_-);
- Pay attention to us, not regular points good article;
- Look at other articles as well;
🎉 You are welcome to write your own learning experience in the comments section, and discuss with me and other students. Feel free to share this article with your friends if you find it rewarding.