Discovering React’s Hidden Gems: 5 Must-Know Features for Pro Developers

Mukesh Prajapati
5 min readJan 10, 2024

--

Whether you are an experienced developer aiming to enhance your skills, or a beginner keen to dive into React, this guide will help you achieve mastery. We cover everything from lazy loading to error boundaries, and performance optimization with Concurrent Mode and Profiler. We are here to support you in discovering the powerful tools of React that will take your web development skills to new levels.

1. Lazy & Suspense — Enhancing Efficiency in React Loading

As a React developer, you can improve the performance of your web applications by using lazy loading and Suspense. React.lazy, in combination with Suspense, enables you to load components in a deferred manner. This means that the components are fetched and rendered only when necessary, instead of upfront during the initialization of your application.

Imagine a scenario where you have a web application with multiple pages, but you don’t want to overload your users by loading all the pages when they first land on your site. In such a situation, React.lazy and Suspense come in handy, allowing you to defer the loading of page components until the user actively clicks on a link to access them. This approach can significantly enhance the initial loading speed of your site, as only the necessary parts are fetched progressively.

To sum it up, using React.lazy and Suspense can help you conserve resources by loading components only when your users require them. This can lead to a more responsive, efficient, and high-performance application.

Example:

import React, { lazy, Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

const HomePage = lazy(() => import('./HomePage'));
const AboutPage = lazy(() => import('./AboutPage'));

function App() {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/about" component={AboutPage} />
</Switch>
</Suspense>
</Router>
);
}

export default App;

We have implemented React.lazy to load the HomePage and AboutPage components only when their respective routes are accessed. The Suspense component provides a fallback UI while the component is being loaded asynchronously. This means that when a user visits the “/about” route, the AboutPage component will be loaded lazily, thus reducing the initial load time of your application.

2. useLayoutEffect — Controlling Layout Updates

useLayoutEffect is a React hook that serves a specific purpose within your components. It’s used when you need to perform certain actions that directly affect the layout or visual aspects of your component immediately after changes to the DOM (Document Object Model). This can be helpful when you want to ensure that your component’s updates are reflected in the layout before the browser paints the screen.

Here’s an example to illustrate its usefulness:

import React, { useState, useLayoutEffect, useEffect } from 'react';

const ExampleComponent = () => {
const [width, setWidth] = useState(0);

useLayoutEffect(() => {
// This code runs synchronously before the component renders
const newWidth = document.getElementById('example').clientWidth;
setWidth(newWidth);
}, []);

useEffect(() => {
// This code runs asynchronously after the component renders
console.log('Component updated');
});

return (
<div id="example">
<p>Component Width: {width}px</p>
</div>
);
};

export default ExampleComponent;

In this example, useLayoutEffect is used to immediately measure the width of the <div> element with the ID “example” and update the component’s state. This ensures that the component’s width is accurate and ready for rendering. It’s especially useful when you need to synchronize your component with the layout.

The difference between useEffect and useLayoutEffect:

  • useEffect: It runs asynchronously after the component has rendered and the browser has painted any changes to the screen. It’s typically used for side effects that don’t require immediate updates to the layout or visuals, such as data fetching or setting up subscriptions.
  • useLayoutEffect: It runs synchronously after the component’s render phase but before the browser paints the screen. This makes it suitable for tasks that require immediate access to the DOM and layout information. It’s often used when you need to perform actions that directly affect the component’s visual representation.

3. Concurrent Mode — Unlocking Performance

Starting from React 17 version, Concurrent Mode is now the default mode for React applications. This means that whenever you render your components, React will automatically generate a new container root to take care of rendering. This change has a significant impact on the performance of your application, greatly improving the user experience.

Concurrent Mode enables React to better prioritize and manage rendering tasks, thereby making your application more responsive, especially on devices with limited resources. By default, React now creates a concurrent root using ReactDOM.createRoot() instead of ReactDOM.render(). This allows React to work on multiple tasks concurrently, handling things like rendering and user interactions in a more efficient and responsive way.

The introduction of Concurrent Mode marks a significant advancement in React’s capabilities, making it easier for developers to build fast and responsive web applications without having to make extensive changes to their code.

4. Error Boundaries — Graceful Error Handling

Error Boundaries are important for handling errors in React apps. They help isolate error-prone UI parts and prevent crashes from impacting the whole app.

Example:

import React from 'react';

class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}

static getDerivedStateFromError(error) {
// Update state to indicate an error occurred.
return { hasError: true };
}

render() {
if (this.state.hasError) {
// You can render any custom fallback UI here.
return <div>Something went wrong. Please try again later.</div>;
}

return this.props.children;
}
}

function UserProfile({ user }) {
return (
<ErrorBoundary>
<div>
<img src={user.profilePicture} alt={user.name} />
<h1>{user.name}</h1>
<p>{user.bio}</p>
<PostsList posts={user.posts} />
</div>
</ErrorBoundary>
);
}

export default UserProfile;

“When you implement an error boundary, it safeguards your application from crashing in case an error occurs within the UserProfile component. Instead, the user will see a friendly message such as “Something went wrong. Please try again later.” This approach ensures a better user experience and enables you to handle errors more gracefully.

Error boundaries are an indispensable part of building resilient and user-friendly React applications. They act as a safety net that catches unexpected issues that may arise during development or at runtime.”

5. Profiler — Performance Insights

React Profiler is a built-in tool that provides invaluable insights into the performance of your React components.

Example:

export const logProfilerData = (id, phase, actualDuration, baseDuration, startTime, commitTime) => {
console.log(`Component ${id} in phase ${phase}:`);
console.log(`- Actual Duration: ${actualDuration} ms`);
console.log(`- Base Duration: ${baseDuration} ms`);
console.log(`- Start Time: ${startTime}`);
console.log(`- Commit Time: ${commitTime}`);
}

export const ArticleContainer = () => {
return (
<Profiler id="article-list" onRender={logProfilerData}>
<ArticleList />
</Profiler>
);
}

Conclusion

Mastering these five React features will not only make you a more proficient developer but also equip you to build high-quality, efficient, and user-friendly web applications. Each concept brings unique advantages to the table, enabling you to create web experiences that stand out in today’s competitive landscape. Therefore, whether you’re a seasoned developer looking to expand your skill set or a curious beginner eager to explore the depths of React, this article will provide you with the knowledge you need to excel in your web development journey. Get ready to take your React expertise to the next level!

--

--