{"id":6994,"date":"2023-01-20T06:21:50","date_gmt":"2023-01-20T06:21:50","guid":{"rendered":"https:\/\/www.ardorsys.com\/blog\/?p=6994"},"modified":"2023-01-20T06:28:35","modified_gmt":"2023-01-20T06:28:35","slug":"lazy-loading-components-on-scroll-in-react-next-js-improve-performance","status":"publish","type":"post","link":"https:\/\/www.ardorsys.com\/blog\/lazy-loading-components-on-scroll-in-react-next-js-improve-performance\/","title":{"rendered":"Lazy Loading Components on Scroll in React Next.js: Improve Performance"},"content":{"rendered":"<p>Next.js is a popular JavaScript framework for building server-rendered React applications. It allows developers to easily create highly performant and scalable web applications. When it comes to have a better user experience with great performance of your web application, using the lazy loading component is the most powerful technique that can load your page faster and engage users as much as they want to be.<\/p>\n<p>Lazy loading components in <a href=\"https:\/\/www.ardorsys.com\/blog\/exploring-the-new-features-and-improvements-of-react-18-in-2023\/\">React<\/a> is a technique that allows you to only load a component when it is needed, which can improve the performance of your application. In Next.js, there are a few ways you can implement lazy loading on scroll to improve the user experience and reduce the amount of data that is loaded on initial page load.<\/p>\n<p>One way to implement lazy loading on scroll is to use the <code>IntersectionObserver<\/code> API. This API allows you to observe a DOM element and determine when it is visible within the viewport. You can create a higher-order component (HOC) that wraps your component and uses the <code>IntersectionObserver<\/code> API to check if it is in the viewport. Once the component enters the viewport, the HOC will set the component to be visible, and it will be rendered.<\/p>\n<blockquote><p>Also read:\u00a0<strong><a href=\"https:\/\/www.ardorsys.com\/blog\/react-vs-angular-which-one-choose-for-your-project\/\" rel=\"bookmark\">React vs Angular: Which One to Choose for Your Project<\/a><\/strong><\/p><\/blockquote>\n<p>Another way to implement lazy loading on scroll is to use the <code>useEffect<\/code> hook to check if the user has scrolled to a certain point on the page. You can create a component that wraps your component and uses the <code>useEffect<\/code> hook to check the scroll position. Once the user scrolls to the specified point, the component will be set to be visible, and it will be rendered.<\/p>\n<p>Additionally, you can use the <code>useRef<\/code> hook to get a reference to a DOM element and then use the <code>useEffect<\/code> hook to check if the element is in the viewport. This approach is similar to using the <code>IntersectionObserver<\/code> API and it allows you to lazy-load elements based on whether they are visible in the viewport.<\/p>\n<p>It&#8217;s important to note that while lazy loading can improve the performance of your application, it may not be necessary for all components. Lazy loading should only be used for components that take a long time to load or that are heavy on resources. Additionally, it&#8217;s better to use Intersection observer API rather than <code>useEffect<\/code> and <code>useRef<\/code> as it could have performance issues if the component is heavy and the user scrolls frequently.<\/p>\n<p>In below example how you can implement lazy loading on scroll using the <code>IntersectionObserver<\/code> API in Next.js:<\/p>\n<ol>\n<li>Create a higher-order component (HOC) that wraps your components and uses the <code>IntersectionObserver<\/code> API to check if it is in the viewport.<\/li>\n<\/ol>\n<pre lang=\"javascript\" escaped=\"true\">\r\nimport React, { useRef, useEffect } from 'react'\r\n\r\nconst withLazyLoad = (WrappedComponent) => {\r\n  return ({ ...props }) => {\r\n    const [isVisible, setIsVisible] = useState(false)\r\n    const ref = useRef(null)\r\n\r\n    useEffect(() => {\r\n      const observer = new IntersectionObserver(\r\n        ([entry]) => {\r\n          if (entry.isIntersecting) {\r\n            setIsVisible(true)\r\n            observer.disconnect()\r\n          }\r\n        },\r\n        { threshold: 0.5 }\r\n      )\r\n      observer.observe(ref.current)\r\n      return () => observer.disconnect()\r\n    }, [ref])\r\n\r\n    return (\r\n      <div ref={ref}>\r\n        {isVisible && <WrappedComponent {...props} \/>}\r\n      <\/div>\r\n    )\r\n  }\r\n}\r\nexport default withLazyLoad;\r\n<\/pre>\n<ol start=\"2\">\n<li>Use the HOC to wrap your components<\/li>\n<\/ol>\n<pre lang=\"javascript\" escaped=\"true\">\r\nimport withLazyLoadfrom '.\/withLazyLoad';\r\nimport HeavyComponent from '.\/HeavyComponent';\r\nconst LazyHeavyComponent = withLazyLoad(HeavyComponent)\r\n\r\nconst MyPage = () => {\r\n  return (\r\n    <div>\r\n      <LazyHeavyComponent \/>\r\n    <\/div>\r\n  )\r\n}\r\n\r\nexport default MyPage\r\n\r\n<\/pre>\n<p>the <code>HeavyComponent<\/code> will only be loaded when it is visible in the viewport, regardless of the scroll position. By using the <code>IntersectionObserver<\/code> API, you can improve the <a href=\"https:\/\/www.ardorsys.com\/web-application-development\/\">performance of your application<\/a> and provide a better user experience.<\/p>\n<p>This example is just a basic example and you can customize it to fit your needs like adding loading spinner or fallback component while the component is not yet visible.<\/p>\n<h3><span style=\"text-decoration: underline;\"><strong>Conclusion<\/strong><\/span><\/h3>\n<p>Lazy loading components on <a href=\"https:\/\/www.ardorsys.com\/blog\/learn-to-create-tabbing-component-in-next-js-14\/\">scroll in Next.js<\/a> is an important technique to improve the performance of your application and provide a better user experience. The <code>IntersectionObserver<\/code> API, <code>useEffect<\/code> hook, and <code>useRef<\/code> hook are all great options for implementing lazy loading on scroll. By only loading a component when it is needed, you can reduce the amount of data that is loaded on initial page load and make your application faster and more responsive.<\/p>\n<p>Also to keep in mind that lazy loading should only be used for components that take a long time to load or that are heavy on resources. Also, it&#8217;s better to use Intersection observer API as it provides better performance and avoids the potential issues that could happen when using <code>useEffect<\/code> and <code>useRef<\/code> hooks.<\/p>\n<p>Next.js, the <code>getInitialProps<\/code> method allows you to check for a user&#8217;s authentication status on the server before rendering the page, as well as you can use this method to check whether the user is on the viewport or not, and then load the component accordingly.<\/p>\n","protected":false},"excerpt":{"rendered":"When it comes to have a better user experience with great performance of your web application, using the lazy loading component is the most powerful technique that can load your page faster and engage users as much as they want to be&#8230;\n","protected":false},"author":1,"featured_media":7002,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[62],"tags":[174,179,64,96],"class_list":{"0":"post-6994","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-react","8":"tag-174","9":"tag-next-js","10":"tag-reactjs","11":"tag-reactjs-development"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts\/6994","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/comments?post=6994"}],"version-history":[{"count":6,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts\/6994\/revisions"}],"predecessor-version":[{"id":7005,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/posts\/6994\/revisions\/7005"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/media\/7002"}],"wp:attachment":[{"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/media?parent=6994"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/categories?post=6994"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.ardorsys.com\/blog\/wp-json\/wp\/v2\/tags?post=6994"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}