It’s Monday, 8 a.m., and React is getting ready for work. It puts its jeans on and then adds a sweater to the final look. Its hair is a bit wild, but it does not seem to bother React. It’s ambient and efficient, ready to conquer the world of frameworks. Being a manager, React has plenty of tasks on its table.
In this article, we will review the daily routine of React, get acquainted with its colleagues and friends, and check out some of its preferences and main features. So put your tech hats on, sit tight, and ride along!
The component lifecycle: React’s routine
Like all managers, React has a set routine and lots of goals. Let’s start by exploring its daily tasks
Mounting
Mounting is one of the primary stages of the component lifecycle where the component is initialized and inserted into the DOM. By means of mounting, React lets its employees know that it’s time to get to work.
The mounting phase normally includes two functions: componentWillMount() and componentDidMount(). The former is invoked before the render function is executed, and the latter is invoked right after the mounting is completed.
useEffect(() => {
window.addEventListener('beforeunload', handleCloseTab);
}, []);
Updating
The updating phase is triggered every time the states and props of a component change. This change could be due to some user events such as pressing a certain key on the keyboard or clicking a mouse button. At this stage, React lets its subordinates know that there have been some alterations made in the initial scope of work and asks them to recheck it.
This phase particularly helps in creating active web pages with React JS. A simple example of this dynamic behavior of active webpages could be one that turns into a dark mode or a light mode when a user presses a key or clicks a certain button on the screen.
useEffect(() => {
if (pickedParticipant) {
handlePickedMatchUp(pickedParticipant.matchUpId);
}
}, [pickedParticipant, handlePickedMatchUp]);
Unmounting
The unmounting phase is normally the last phase of the component’s lifecycle. The componentWillUnmount() function is invoked during this stage, and the component is finally removed from the page. The manager lets the employees go home.
The unmounting stage is very important, as it cleans up any open connections such as WebSockets or intervals. It also denotes the end of the component’s lifecycle.
useEffect(() => {
window.addEventListener('beforeunload', handleCloseTab);
return () => {
window.removeEventListener('beforeunload', handleCloseTab);
};
}, []);
It’s really important for React to see that everything is in order, so it does its best to guarantee a smooth work process.
Now that we are aware of how React likes to spend its day, let’s proceed to meeting its components, or employees.
React components, or employees
React is designed around the concept of component-based architecture. Its components, or employees, are all multi-functional and eager to help their manager with the most challenging tasks. The smaller components can be put together to form bigger ones, and each one of them can be reused, even across different projects.
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
Leaving aside some context providers we can think about App component as a root that renders into DOM.
A component can't receive data from its siblings or children directly so how would data move around. The parent component passes the data to its child as a props. Parents have state to hold the data and send the child function that can receive data and set it to this state. The child then passes the data to this function to update the state of the parent.
But of course there is a more efficient way to share data in deep nested tree nodes. Previous cases could cause an issue called "prop drilling". If your parent should pass data to the deep level nested component, children in between will just pass it down without using this data. For these cases we have Context.
You can just wrap your node with Context Provider and have some state there. After that deep nested children will be able to access and modify this data without props passing. Good example of usage is a global Auth Context.
Quick Tip. Don't forget about rerender optimizations. Before using React.memo and other memoization tools you should correctly identify where your state should live. Try to keep it as close as you can to the components that use it.
Best React component libraries
React component libraries make development a breeze. They are fully reusable and provide a lot of flexibility due to their high modularity. Here are some of the most useful component libraries of React.
-
React Bootstrap
React Bootstrap is one of the most-used React component libraries that replaces bootstrap JavaScript with React. This employee makes sure all the work is done faster and efficiently. It gives a lot of liberty to play with responsive web components.
-
Material UI React
Material UI has all the material design elements you can directly use in your React projects. Its sleek and simplistic elements allow users to create a high-quality digital experience. Material UI has a creative brain that offers the most sophisticated design concepts.
-
Ant Design React
Ant Design React is particularly useful for creating rich and engaging user interfaces. It brings the Material UI’s ideas to life. It supports multiple languages and uses Less.js for styling components. With Ant design, you can easily customize designs with different buttons, grids, breadcrumbs, icons, and dropdowns.
Quick Tip: When working with React, don’t forget about re-rendering optimizations. Before using React.memo and other memorization tools, you should correctly identify where your state should live. Try to keep it as close as you can to the components that use it.
It’s time to check out the skills React recently achieved.
React Hooks - the story of how React got new skills
React Hooks were introduced in the 16.8 version and were total game-changers at the time. This feature allows you to use state and other React features without writing a class.
Before Hooks, it was hard to reuse stateful logic between components. With custom hooks, you can easily extract your logic from the component and reuse it without any hierarchical changes. React Hooks are backward-compatible, which means that there aren’t any breaking changes. Plus, Hooks do not replace your knowledge of React concepts.
In plain words, now that React has Hooks, it can respond to any events quicker and, thus, do its job better.
Rules for Hooks
There are only two rules for using Hooks.
-
Hooks can only be called at the top level. This means that they cannot function inside conditions or nested loops.
-
You can only call hooks from React function components or custom hooks. Calling them from regular JavaScript functions does not work.
Quick Tip: Previously, you could add a state to a function component only by converting it to a class. With Hooks, it is possible to do the same inside the existing function component
Let’s move on to React State now.
React State: inner values always come first
The state of a component is an object that carries information that may vary over its lifetime. React components can have their own states. These states can be created using hooks like [useState] and [useReducer].
const [isActive, setIsActive] = useState(false);
How to manage states
Component states can be managed through a particular set of functions. Other than that, they are more or less immutable — this is the way it should be to avoid any bugs.
You should never mutate the state of a component directly, but only through the update function. Another thing you need to be careful about is that the [useState] callback does not merge the state as [setState] in class components did. This means that you have to return a full object in callback even if you want to change only one of its properties.
Quick Tip: Don't be afraid to split your state into multiple [useState]. Despite the fact that the components re-render after a state update, it does not mean they will re-render as many times as you call set state functions.
Let’s move on to one of the most important React concepts and its best friend — JSX.
JSX: the best friend of React
JSX is very friendly and easy-going — it was JSX who introduced React components to HTML and taught them how to cooperate.
JSX stands for JavaScript XML, a simple syntax extension of JavaScript. JSX allows users to directly write HTML in React and produce React elements. React uses Babel to compile JSX down to [React.createElement] calls.
<div>
{!!count && ( <p className={styles.count}>Users (${count})`}</p> )}
<button
type="button"
className={styles.addBtn}
onClick={handleToggleLanguageModal}
>
Create User
</button>
</div>
Why should you use JSX?
The reason for using JSX is quite obvious. It makes it very simple to build React applications. With JSX, the UI automatically stays updated with the user-count value, and you don’t have to care about any markup or logic consistency. Also, it works a little faster than normal JavaScript, as it automatically performs optimizations while translating to regular JavaScript.
Quick Tip: React components require you to return only one element. So, don’t wrap your list of children nodes into HTML elements if you don’t actually need it. This will just add extra nodes to the real DOM. Instead, you could use either the React.Fragment function or just an empty tag <> … <> as a shortcut.
React’s colleague: virtual DOM
It’s time to get to know virtual DOM, React’s colleague that takes care of all the paperwork, saving React precious time. Let’s dig deeper.
React allows you to build UIs virtually, without directly operating through a DOM. It uses the concept of a virtual DOM, which is essentially a copy of the original DOM kept in the memory and synced with the real DOM through a library such as ReactDOM.
With a virtual DOM, you can implement complete event systems without interacting with actual DOM events. All you need to do is convey how you want a component to be rendered, and React will translate this declarative abstract to actual UIs in the browser.
Pros & cons of a virtual DOM
Here are a few pros and cons of using a virtual DOM via React.
Pros
-
Virtual DOMs usually perform diff algorithms very efficiently.
-
They are simple and lightweight and hence do not consume a lot of system resources.
-
Virtual DOMs can work independently of React.
-
They allow for building applications without having to worry about state transitions.
Cons
-
Since the virtual system is practically an in-memory copy of the DOM, it has a higher memory usage.
-
Virtual DOMs can not differentiate between static and dynamic elements.
Difference between DOMs and Virtual DOMs
The virtual DOM is represented as an object and acts like a copy of the real DOM in the memory. Since manipulations with objects are much faster, the virtual DOM responds more efficiently in this case. React performs the manipulations on the object and compares virtual and real DOM trees for any changes. After that, it updates only the nodes that have changed and hence saves a lot of time and system resources.
React’s assistants: props
Props help React in its managing role, giving additional instructions to the components or employees. In tech language:
Props are React fundamentals for moving read-only attributes across React components. They allow you to move around data, such as numbers, strings, functions, objects, arrays, etc., to a component. If you have multiple components, you can pass data from one to another. PropTypes is a separate library; you can use it or any other tool for typing your props and React application. The most modern technology that React really likes to work with is TypeScript.
The role of props is quite important since, if the component receives the wrong data, it can lead to unexpected errors in your app. Props make sure the job is done right every time.
Quick Tip: Props can be passed between components by adding them when the component is called, similar to how you would pass arguments when calling a JS function. You may also define JavaScript default parameters using another special property called [defaultProps]. This is particularly for cases where props are not being passed into the component on call.
Advanced React concepts, beliefs, and bonus tips
React believes in a green future, as it was built around the primary idea of code reusability. React patterns were developed to deal with the problems of applying old codes, writing new reusable code, and repeating state logic. All of this comes with one end goal — writing better components and saving the environment.
Being really competitive and ambitious but outgiving, React still has plenty of ideas and plans to work on. It strives to improve the world for itself and those around it. It prepared some advanced React frameworks and eco-friendly tips that can help you become a better developer:
-
Using React Fragments instead of < div> elements makes grouping elements more efficient.
-
Context surpasses the need of passing props down the component tree manually. So, if you have multiple components that need values, you can start relying on Context more.
-
Creating a React component and using it as a parent to handle errors creates Error Boundaries. These boundaries prevent and control the errors of all child components.
-
Use production built in the LIVE environment.
-
Use Refs to interact with child nodes to trigger animations, select text, or manage the focus.
-
Using code splitting allows you to create multiple outputs and improve website load times.
-
Using Static Type Checking with a simple tool like TypeScript can prevent errors by catching mistakes early.
You can learn more about all advanced React components on the React Resources website, as they have an amazing collection of articles and tutorials that could be of help.
Conclusion
All friendships start with building a mutual understanding. Similarly, learning React fundamentals will help you become great friends with React, which will, in turn, make you a brilliant developer.
If you are just starting out and need any sort of help with React, our Geniusee specialists are always ready to help. Get in touch with us today and be sure that we will help you create a successful product!