The React library makes life easier for developers who have to create sophisticated user interfaces. It is enough for the programmer to prepare simple descriptions of graphical representations for application states, and React, when changing data, will effectively update and redraw only those components that were affected by these changes. However, in order to create high-quality projects on React, a programmer needs to make efforts aimed at mastering this library and development aids.
The author of the article, the translation of which we are publishing today, wants to share with the audience of React-developers nine useful tips aimed at improving the quality of the code. These tips cover a fairly wide range of topics, from tools to programming style.
1. Checking the code using the linter
Improving the quality of programs is facilitated by the use of a good system for checking code for errors. Typically, such checks are performed using linter programs. If the developer has a well-thought-out set of linting rules, the code editor will be able to automatically track the appearance of what can lead to problems. However, early detection of potential problems is only one of the tasks that can be solved, for example, using ES Lint . No less important is the fact that the use of such tools leads to the fact that the developer will always be aware of the latest developments in programming for React.
Consider an example.
import react from 'react';
/* Другие команды импорта */
/* Код */
export default class App extends React.Component {
render() {
const { userIsLoaded, user } = this.props;
if (!userIsLoaded) return ;
return (
/* Код */
)
}
}Suppose that in a function render(), we need to turn to a new property this.props.hello. If the linter finds out that this property has not passed validation, it will immediately report this:
'hello' is missing in props validation (react / prop-types)
The constant use of the linter helps to improve the quality of programs and has a beneficial effect on the development of the programmer, improving the way he perceives the code. Receiving such hints, the programmer will very soon learn not to make the mistakes that the code verification system “swears”.
In order to equip your development environment with a JavaScript liner, you can use the ESLint resource or look at the Airbnb style guide page . You can also install the ESLint plugin for React.
2. Using propTypes and defaultProps
Above, we talked about how the linter behaves when trying to work with a property that has not passed validation. Now consider the following example.
Here, if you want the property userIsLoadednot to be necessary, you will need to add the following to the code:
static defaultProps = {
userIsLoaded: false,
}
Using mechanisms PropTypeand, defaultPropswe can describe the properties used in components, which allows React to organize their validation, which improves the quality and stability of programs. In this case, we tell the system that the property userIsLoadedmust have a logical value, and that its default value is false, which makes its specification optional. If the property is required, then there is no need to set its default value.
Here, in addition, it is worth saying that it is not recommended to use too “blurry” types of properties like Objector Array.
That is why it shows the use shapefor validation of the object userwithin which it exists id, propTypewhich isstring. In this case, the whole object is necessary user.
The presence of propTypesand defultProp, for each component that uses it props, plays a large role in developing robust React applications.
When a property does not receive the expected data, the corresponding entries appear in the error log, which allow the programmer to know that he is either transmitting something wrong to the component or not transmitting something such that the system expects to appear. This simplifies the search for errors, especially when it comes to working with many components designed for reuse. In addition, the code in which these mechanisms are used acquires self-documenting properties.
Note that unlike earlier versions of React, the mechanism is nowpropTypesIt is not included in React by default and to use it you will need to add this feature to the project as a dependency. In order to do this, you can use the npm-package prop-types .
3. About creating new components
Consider an example. The code snippet shown below has a component Profile. Inside this component there are components MyOrderand MyDownloads.
The code of all these components could be written right here, since data is being loaded from the same place represented by the object user. However, this approach will turn small components into one giant component. All this leads us to the question of when to create new components.
Although there is no strict rule regarding the transfer of code into components, before doing this, it is worth looking for answers to the following questions:
Is code functionality cumbersome?
Does this code represent an independent phenomenon?
Are you planning to reuse this code?
If at least one of these questions is answered positively, then you need to move this code to the component.
However, it should be borne in mind that few people will like to see huge components in program texts, consisting of 200-300 lines of code and full of various auxiliary mechanisms.
4. Components, pure components, stateless functional components. What to choose?
It is important for a React developer to know when to use components (Component), pure components (PureComponent) and stateless functional components (Stateless Functional Component).
In the examples above, you might notice that instead of declaring Profilehow Component, we describe it as PureComponent.
We will deal with the features of various types of components.
▍ Functional components without state
Stateless functional components are one of the most common types of components in the React developer’s arsenal. They provide a convenient and concise way of creating components that do not use states , references to elements or life cycle methods .
const Billboard = () => (
React
React
Lorem Ipsum
);
The essence of such components is that they are ordinary functions and have no state. In fact, these are simply functions that return JSX.
▍ Clean components
Typically, when a component receives a new property, React redraws that component. However, sometimes a component receives new properties that, in fact, have not changed, but this also leads to the fact that React redraws it.
The use of pure components , PureComponentand helps prevent the like. For example, if a property is a string or a boolean, and it changes, PureComponentit recognizes it, but if the property changes inside the object, it PureComponentwill not cause re-rendering.
How do I know that React is performing unnecessary component re-rendering operations? You can use why-did-you-update for this.- A great package for React. The tools in this package let you know about the operations of re-rendering components that you can do without.
Messages about the possibility of avoiding re-rendering of components
After it becomes clear that unnecessary re-rendering is being applied, you can use, instead of Component, PureComponentto avoid this unnecessary rendering.
5. React Developer Tools
If you are serious about becoming a professional React developer, then the React developer tools should be included in your workflow. If you have already written on React, then you probably saw the suggestions displayed in the console to use the developer tools. They are available for major browsers such as Chrome and Firefox .
Developer tools give access to the structure of the React application and allow you to see all the properties and states used in the project. They are an excellent tool for exploring the internal structure of components and debugging applications.
6. Using built-in conditional expressions
Although some might not like this approach, I found that using built-in conditional expressions made the texts of my programs much cleaner.
Take a look at this piece of code.
{isRole('affiliate', user._id) &&
}
Here there is a function that checks the role of the user (it should have a value 'affiliate'), after which there is an operator &&and a component .
Here's what I like about all of this:
I did not need to write a separate function.
I did not need to use an additional expression ifin the function render.
I did not have to create a “link” leading to some other place in the component.
Writing inline conditional expressions is pretty straightforward. It all starts with writing a conditional expression. If, for example, writing is simple instead of an expression true, this will lead to the fact that the component will always be displayed.
Next, we associate the conditional expression with , using &&. Thanks to this approach, a component will be output only if the conditional expression returns true.
7. Snippet libraries
Libraries of snippets, pre-prepared template code fragments, accelerate the development process and reduce the number of errors. Here's what their use looks like. I, working in VS Code, create a new .js file. I enter the text in it rcand see what is shown in the figure below.
Snippets
If you select what you need and press Enter, the corresponding code fragment will get into the editor.
The snippet inserted into the Snippet editor
is a very useful thing, as they not only help to prevent small errors from entering the code, but also help the developer find and use relevant examples of code design.
If you, while working with React, feel that some things are eluding your understanding, you should look for training resources that reveal the basics of the internal mechanisms of React. In my case, this resource was a series of five materials called React Internals . She helped my professional growth. I believe this series will be useful to those who have a general idea of what they want to achieve, but are not completely sure how to do it.
9. The use of Bit and StoryBook to organize convenient work with components
Bit is a great tool for turning components into building blocks that can be used in various applications. In this case, the changes made to the components in different places of their application can be synchronized.
In addition, Bit can be used to organize components at the command level, to convert their sets into shared libraries, which makes it easier to work with them. There is also an interactive sandbox , tools for testing components in isolation, and other features.
Storybook- This is an interactive development environment for user interface components, which can help in working with component libraries, in analyzing the various states of components. It simplifies the process of developing and testing components.
The StoryBook system can accelerate the development of React components due to the presence of a specialized environment in which you can see the components in action during experiments with their properties.
Summary
How to improve the quality of React application code? According to the author of the material, the following contributes to this:
Using a code verification system.
The use of propTypes and DefaultProps.
A sound approach to creating new components.
Knowledge of the features of components, pure components and stateless functional components.
Using React Developer Tools.
The use of built-in conditional expressions.
Using snippet libraries.
Developing a developer through the development of quality React guides.
The use of tools such as Bit and StoryBook, which can improve the development and use of components.
We hope you find these recommendations useful.
Dear readers! What advice could you give to those React developers who want to improve the quality of their code and grow professionally?