Hello Readers, CoolMonkTechie heartily welcomes you in this article.
In this article, we will learn about fundamental Best Practice and Tips in React Application. For any application development, fundamental best practice and tips are most important for developer who developed the application. We will discuss the below most fundamental of React best Practices one by one:
- Keep components small and function-specific
- Reusability
- Consolidate duplicate code – DRY your code
- Put CSS in JavaScript
- Comment only where necessary
- Name the component after the function
- Use capitals for component names
- Mind the other naming conventions
- Separate stateful aspects from rendering
- Code should execute as expected and be testable
- All files related to any one component should be in a single folder
- Use tools like Bit
- Use snippet libraries
- Write tests for all code
- Use ES Lint for better coding conventions.
A famous quote about learning is :
“ An investment in knowledge pays the best interest.”
So Let’s begin.
1. Keep components small and function-specific
As we all know, with React, it’s possible to have huge components that 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:
- Function-specific components can be standalone, which makes testing and maintenance easier.
- Each small component can be reused across multiple projects.
- Components executing general functions can be made available to the community.
- 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.
The balance between creating one concise component and creating multiple function-specific components can vary from organization to organization. After all, you can have as many components as you want, and recombine them in any way you want to achieve the same end result.
2. Reusability
By sticking to the rule of one function = one component, you can improve the reusability of components. What this means is that you should skip trying to build a new component for a function if there already exists a component for that function.
Reusability is important, so keep creation of new components to the minimum required.
For example, you can even go further and create a Button
component that can handle icons. Then, each time you need a button, you’ll have a component to use. Making it more modular will allow you to cover many cases with the same piece of code. You have to aim somewhere in the middle. Your components should be abstract enough, but shouldn’t be overly complex.
class IconButton extends React.Component {
[...]
render() {
return (
<button onClick={this.props.onClick()}>
<i class={this.props.iconClass}></i>
</button>
);
}
}
3. Consolidate duplicate code – DRY your code
A common rule for all code is to keep it as brief and concise as possible.
Here, React best practices also instruct you to keep code brief and precise. One way to do this is to avoid duplication – Don’t Repeat Yourself (DRY).
You can achieve this by scrutinizing the code for patterns and similarities. This relies heavily on the reusability principle in React. Let’s say you want to add multiple buttons that contain icons, instead of adding the markup for each button, you can simply use the IconButton
component that we shown above. You could even go further by mapping everything into an array.
const buttons = ['facebook', 'twitter', 'youtube'];
return (
<div>
{
buttons.map( (button) => {
return (
<IconButton
onClick={doStuff( button )}
iconClass={button}
/>
);
} )
}
</div>
);
4. Put CSS in JavaScript
When you start working on a project, it is a common practice to keep all the CSS styles in a single SCSS file. The use of a global prefix prevents any potential name collisions. However, when your project scales up, this solution may not be feasible.
There are many libraries that enable you to write CSS in JS. EmotionJS and Glamorous are the two most popular CSS in JS libraries.
5. Comment only where necessary
Attach comments to code only where necessary. This is not only in keeping with React best practices, it also serves two purposes at the same time:
- It’ll keep code visually clutter free.
- You’ll avoid a potential conflict between comment and code, if you happen to alter the code at some later point in time.
6. Name the component after the function
It’s a good idea to name a component after the function that it executes so that it’s easily recognizable.
For example, ProductTable
– it conveys instantly what the component does. On the other hand, if you name the component based on the need for the code, it can confuse you at a future point of time.
One more example, it’s preferable to name a component Avatar
so that it can be used anywhere – for authors, users or in comments. Instead, if we name the component AuthorAvatar
in the context of its usage, we’d be limiting the utility of that component.
Besides, naming a component after the function makes it more useful to the community as it’s more likely to be discovered.
7. Use capitals for component names
If you’re using JSX (a JavaScript extension), the names of the components you create need to begin with uppercase letters. For instance, you’ll name components as SelectButton
instead of selectbutton
, or Menu
instead of menu
. We do this so that JSX can identify them differently from default HTML tags.
8. Mind the other naming conventions
When working with React, you are generally using JSX (JavaScript Extension) files. Any component that you create for React should therefore be named in upper camel case. This translates to names without spaces and the capitalizing the first letter of every word.
If you want to create a function that submits a form, you should name it SubmitForm
in upper camel case, rather than submitForm
, submit_form
, or submit_form
. Camel case is also called Pascal case.
PascalCase is a naming convention in which the first letter of each word in a compound word is capitalized. Software developers often use PascalCase when writing source code to name functions, classes, and other objects.
PascalCase is similar to camelCase, except the first letter in PascalCase is always capitalized. Below are some examples.
- PascalCase: NewObject;
- camelCase: newObject;
- PascalCase: LongFunctionName()
- camelCase: longFunctionName()
Both PascalCase and CamelCase help developers distinguish words within names. For example, “LongFunctionName” is more readable than “longfunctionname.”
9. Separate stateful aspects from rendering
Components in React can be stateful or stateless.
Stateful components store information about the component’s state and provide the necessary context. In contrast, stateless components have no memory and cannot give context to other parts of the UI. They only receive props (inputs) from parent component and return you JSX elements. They are scalable and reusable, and similar to pure function in JavaScript.
One of React best practices is to keep your stateful data-loading logic separate from your rendering stateless logic. It’s better to have one stateful component to load data and another stateless component to display that data. This reduces the complexity of the components.
The later React versions v16.8 have a new feature – React Hooks, which write stateful function-related components. This may eventually eliminate the need for class-based components.
For example, your app is fetching some data on mount. What you want to do is manage the data in the main component and pass the complex render task to a sub-component as props.
import RenderTable from './RenderTable';
class Table extends Component {
state = { loading: true };
render() {
const { loading, tableData } = this.state;
return loading ? <Loading/> : <RenderTable data={tableData}/>;
}
componentDidMount() {
fetchTableData().then( tableData => {
this.setState( { loading: false, tableData } );
} );
}
}
10. Code should execute as expected and be testable
The code you write should behave as expected, and be testable easily and quickly. It’s a good practice to name your test files identical to the source files with a .test
suffix. It’ll then be easy to find the test files.
In React to test component we use Jest and Enzyme. Jest was created by Facebook and is a testing framework to test javascript and React code. Together with Airbnb’s Enzyme, which is a testing utility, makes it the perfect match to easily test your React application.
11. All files related to any one component should be in a single folder
Keep all files relating to any one component in a single folder, including styling files.
If there’s any small component used by a particular component only, it makes sense to keep these smaller components all together within that component folder. The hierarchy will then be easy to understand – large components have their own folder and all their smaller parts are split into sub-folders. This way, you can easily extract code to any other project or even modify the code whenever you want.
For instance, for the Form
component, all pieces such as CSS files, icons, images, tests and any other sub-components relating to Form should all reside in the same folder. If you name files sensibly, and keep related files together logically, you’ll not have any difficulty finding them later.
12. Use tools like Bit
One of React best practices that helps to organize all your React components is the use of tools like Bit.
These tools help to maintain and reuse code. Beyond that, it helps code to become discoverable, and promotes team collaboration in building components. Also, code can be synced across projects.
13. Use snippet libraries
Code snippets help you to keep up with the best and most recent syntax. They also help to keep your code relatively bug free, so this is one of the React best practices that you should not miss out on.
There are many snippet libraries that you can use, like, ES7 React, Redux, JS Snippets, etc.
14. Write tests for all code
In any programming language, adequate testing ensures that any new code added to your project integrates well with existing code and does not break existing functionality. It is a good idea to write tests for any new component that you create. As a good practice, you should create a __Test__
directory within your component’s directory to house all relevant tests.
You can broadly divide tests in React into two parts: testing the functionality of components using a React app, and tests on your complete application once it renders in the browser. You can use cross browser testing tools for tests in the latter category.
For the former, you can use a JavaScript test runner, Jest to emulate the HTML DOM using jsdom
to test React components. While a completely accurate test is only possible in a browser on a real device, Jest provides a good approximation of the real testing environment during the development phase of your project.
15. Use ES Lint for better coding conventions
Linting is a process wherein we run a program that analyses code for potential errors.
Well run projects have clear consistent coding conventions, with automated enforcement. Besides checking style, linters are also excellent tools for finding certain classes of bugs, such as those related to variable scope. Assignment to undeclared variables and use of undefined variables are examples of errors that are detectable at lint time.
That’s all about React fundamental best practices and tips.
Conclusion
In this article, We understood the list of React fundamental best practices is going to help you put your projects on the right track, and avoid any potential problems later down the road.
Thanks for reading ! I hope you enjoyed and learned about React fundamental best practices list. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.
Thanks again Reading. HAPPY READING !!???