15 React Best Practices for Superior Development
React Clean Coding And Best Practices Every Frontend Developer Should Know About
Photo by Lautaro Andreani on Unsplash
Table of contents
1. Embrace Visual Studio Code
VS Code is Highly Recommended as IDE
Visual Studio Code, commonly referred to as VS Code, stands as a powerhouse for React developers. This feature-rich Integrated Development Environment (IDE) offers a plethora of extensions that can transform your development environment into a productivity haven.
Here are some indispensable extensions tailored for React development:
Prettier: Ensure your code remains consistently formatted.
ESLint: Detect and fix code errors and enforce coding standards.
JavaScript (ES6) code snippets: Simplify your coding with useful snippets.
Reactjs code snippets: Boost productivity with React-specific code snippets.
Auto import: Effortlessly manage your imports.
2. Harness the Power of ES6 Syntax
Use ES6 Syntax
Clean and concise code is a hallmark of effective development. Embrace ES6 syntax to streamline your codebase and make it more elegant.
2.1. Write Arrow Functions
In ES6, arrow functions provide a concise way to define functions.
// ES5
function getSum(a, b) {
return a + b;
}
// ES6
const getSum = (a, b) => a + b;
2.2. Utilize Template Literals
Template literals in ES6 offer a more readable and flexible way to concatenate strings.
// ES5
var name = "Bilal";
console.log("My name is " + name);
// ES6
const name = "Bilal";
console.log(`My name is ${name}`);
2.3. Embrace const and let
ES6 introduces block-scoped variables with const
and let
. Use const
for immutable values and let
for mutable ones.
// ES5
var fruits = ["apple", "banana"];
// ES6
let fruits = ["apple", "banana"];
fruits.push("mango");
const workingHours = 8;
2.4. Leverage Object Destructuring
Object destructuring simplifies the process of extracting values from objects.
var person = {
name: "John",
age: 40,
};
// ES5
var name = person.name;
var age = person.age;
// ES6
const { name, age } = person;
2.5. Define Objects Concisely
In ES6, object definitions become more concise and readable.
var name = "John";
var age = 40;
var designation = "Full Stack Developer";
var workingHours = 8;
// ES5
var person = {
name: name,
age: age,
designation: designation,
workingHours: workingHours,
};
// ES6
const person = { name, age, designation, workingHours };
ES6 syntax introduces an array of features and flexibility that can greatly improve your coding experience.
3. Mind the key Prop With map in JSX
Don't Forget key Prop With map in JSX
When mapping elements from an array in JSX, it's crucial to assign a unique key
prop to each element. This ensures optimal rendering performance and helps React identify and manage elements efficiently.
const students = [{ id: 1, name: 'Bilal' }, { id: 2, name: 'Haris' }];
// In the return function of a component
<ul>
{students.map(({ id, name }) => (
<li key={id}>{name}</li>
))}
</ul>;
4. Maintain Naming Conventions
Component Name Should be in PascalCase
Consistent naming conventions improve code readability and maintainability. In React, it's customary to use PascalCase for component names.
const helloText = () => <div>Hello</div>; // Avoid
const HelloText = () => <div>Hello</div>; // Preferred
Variable & Function Names Should be in camelCase
For variables and functions, camelCase is the preferred naming convention.
const working_hours = 10; // Avoid
const workingHours = 10; // Preferred
const get_sum = (a, b) => a + b; // Avoid
const getSum = (a, b) => a + b; // Preferred
ID & Class Names Should be in kebab-case
When working with HTML elements, use kebab-case for ID and class names.
<!-- Avoid -->
<div className="hello_word" id="hello_world">Hello World</div>
<!-- Preferred -->
<div className="hello-word" id="hello-world">Hello World</div>
5. Handle null & undefined Gracefully
Always Check null & undefined for Objects & Arrays
Neglecting null and undefined in the case of objects & arrays can lead to errors. Always check for them in your code to ensure smooth execution.
const person = {
name: "Haris",
city: "Lahore",
};
console.log("Age", person.age); // Error
console.log("Age", person.age ? person.age : 20); // Correct
console.log("Age", person.age ?? 20); // Correct
const oddNumbers = undefined;
console.log(oddNumbers.length); // Error
console.log(oddNumbers.length ? oddNumbers.length : "Array is undefined"); // Correct
console.log(oddNumbers.length ?? "Array is undefined"); // Correct
6. Keep Styling Separate
Avoid Inline Styling
Inline styling can clutter your JSX code. It's best practice to use classes and IDs for styling and keep your styles in separate .css files.
const text = <div style={{ fontWeight: "bold" }}>Happy Learning!</div>; // Avoid
const text = <div className="learning-text">Happy Learning!</div>; // Preferred
In a separate .css file:
.learning-text {
font-weight: bold;
}
7. Prioritize React State Over DOM Manipulation
Avoid DOM Manipulation
Instead of manipulating the DOM directly, leverage React state to control the visibility and behaviour of elements.
Bad Approach
<div id="error-msg">Please enter a valid value</div>
Good Approach
const [isValid, setIsValid] = useState(false);
<div hidden={isValid}>Please enter a valid value</div>;
Set isValid
to false
or true
where you have logic for validating a value.
8. Clean Up Event Listeners
Always Remove Every Event Listener in useEffect
When adding event listeners in React components, it's vital to clean them up to prevent memory leaks. Use the useEffect
hook to add and remove event listeners as needed.
const printHello = () => console.log("HELLO");
useEffect(() => {
document.addEventListener("click", printHello);
return () => document.removeEventListener("click", printHello);
});
9. Embrace Reusability
Avoid Repetition, Use Generic Components
Creating generic components for similar groups of elements promotes code reusability and maintainability. You can render these components based on the props you