In this blog, we will list React best practices, methods, and techniques that will help us stay consistent during the app development.
Its components are the building blocks of a react project. Here are some of the React best practices that can be considered while coding with React in the component state and component hierarchy.
1. Keep components small
We know that with React, it is possible to have very huge components that can execute a number of tasks. But a better way to design components is to keep them small, so that one component corresponds to one function. Ideally, a single component should render a specific bit of your page or modify a particular behavior. There are many advantages to this:- Each small component can be reused across multiple projects.
- With smaller components, it’s easier to implement performance optimizations.
- It’s easier to update smaller components.
- Bigger components have to perform harder and may be difficult to maintain.
2. Use propTypes for Type Checking and Preventing Errors
As your app grows, you can catch a lot of bugs with type checking. For some applications, you can use JavaScript extensions like Flow or TypeScript to type check your whole application. But even if you don’t use those, React has some built-in type checking abilities which are known as propTypes.3. Write DRY(Don’t Repeat Yourself) Code
A common rule for all code is to keep the code as concise as possible. Repeating the code in several places leads to the increase in the overall bundle size and if we want to change the same functionality dependant code, we need to change it in all place which in turn will kills the time of the development.4. Comment only where necessary
Add comments to the code wherever you feel that the comment will increase the readability of the complex functions. Avoid using comments to the code, if you want the code to be used in the future, give some meaningful description on how and why that piece of code is commented.5. Try to Avoid Unnecessary Div
-
- When there is a single component to be returned, there is no need to use < div >
return (
< div >
< Button >Close< /Button >
< /div >
);
-
- When there are multiple components to be returned, use or in shorthand form <> as shown below:
return < Button > Close < /Button >;
6. Use Destructuring to Get Props
Destructuring was introduced in ES6. This type of feature in the javascript function allows you to easily extract the form data and assign your variables from the object or array. Also, destructuring props make code cleaner and easier to read.-
- Example 1: There is an object named “info”.
const info = {
title: ‘once upon a time’,
protagonist: {
name: ‘Emma Swan’,
enemies: [
{name: ‘Regina Mills’, title: ‘Evil queen’},
{name: ‘Zelena’, title: ‘The Witch’},
{name: ‘PeterPan’, title:’The boy grown up’}
]
}
}
-
- To access properties of object, you need to write:
const title = info.title;
const protagonistName = infor.protagnoist.name;
const enemy = info.protagonist.enemies[1]
-
- Which can be written as following with destructuring:
const {title, protagonist: {name: protagonistName }, protagonist: {enemies:[,{name:enemyName}]}} = info;
7. Alignment
Follow the below alignment styles for JSX syntax, if props fit in one line then keep it on the same line otherwise indent those lines usingeslint: react/jsx-closing-bracket-location react/jsx-closing-tag-location.
8. Follow linting rules, break up lines that are too long
Linting is a process wherein we run a program that analyses code for potential errors.Mostly, we use it for language-related issues. But it can also fix many other issues automatically, particularly code style. Using a linter in your React code helps to keep your code relatively error and bug-free.
9. Code Busting
A website contains a lot of files— JavaScript, CSS, HTML, and images—that your web browser must download before it can be displayed. If you had to get those files from the web server every time you refreshed the page or clicked a hyperlink, your browser would have to re-download all those files each and every time, wasting bandwidth and increasing the time it takes to load the webpage. This is where cache comes into play. Your browser caches, or stores, all these files on your computer so it doesn’t have to re-download them every time you refresh. Those files are saved (cached) just once—the first time you visit the website.When a static file gets cached it can be stored for very long periods of time before it ends up expiring. This can be an annoyance in the event that you make an update to a site however, since the cached version of the file is stored in your visitors’ browsers, they may be unable to see the changes made.
Cache busting solves the browser caching issue by using a unique file version identifier to tell the browser that a new version of the file is available. Therefore the browser doesn’t retrieve the old file from cache but rather makes a request to the origin server for the new file. More details on how to implement cache busting on React apps can be found in another article.
10. Proxy Setup
If you’ve built your webapp (webapp1.com) that had to call API’s from a different domain(webapp2.com), you’ve probably had encountered with CORS issue. Browser’s default same-origin policy kicks in and blocks the request. CORS is a feature that allows webapp2.com to tell the browser that it’s okay for webapp1.com to make requests to it, by sending certain HTTP headers.Create React App allows us to replicate this setup in development, so that we don’t have to deal with CORS there either. So to avoid this we can use ‘http-proxy-middleware’ npm library.s
const { createProxyMiddleware } = require(‘http-proxy-middleware’);
const url = ‘https:webapp2.com’;
module.exports = function(app) {
app.use(
createProxyMiddleware(‘/api/’, {
target: url,
// wfapi-dev.pdsnew.com
changeOrigin: true,
}),
);
};
Referring from the above code, when the API starts with ‘/api’, it will redirect to the backend proxy server.