Optimize nextjs performance by lazy load and hydrate under the fold

Overview

next-lazy-hydrate

npm package Build Status Downloads Issues Semantic Release

Lazy load and hydrate component on demand. Deal with Nextjs performance without compromise.

Feature

  • Render component in SSR (Good for SEO)
  • Only load JS bundle and hydrate when needed (Good for page Speed)

This package is heavily based on https://github.com/valcol/react-hydration-on-demand

Next lazy hydrate

Before After
Screen Shot 2022-06-05 at 22 31 29 Screen Shot 2022-06-05 at 22 31 19
https://next-lazy-hydrate-origin.vercel.app/ https://next-lazy-hydrate-optimized.vercel.app/
Live check PageSpeed Live check PageSpeed

Read more about Islands Architecture here

Install

npm install next-lazy-hydrate

Usage

import lazyHydrate from 'next-lazy-hydrate';

// Lazy hydrate when scroll into view
const WhyUs = lazyHydrate(() => import('../components/whyus'));

// Lazy hydrate when users hover into the view
const Footer = lazyHydrate(
  () => import('../components/footer', { on: ['hover'] })
);

const HomePage = () => {
  return (
    <div>
      <AboveTheFoldComponent />
      {/* ----The Fold---- */}
      <WhyUs />
      <Footer />
    </div>
  );
};

Demo how to use it

API

lazyHydrate(dynamicImport, options?)

dynamicImport

Type: () => Promise

A function return import() in dynamic loading type

Options

on: Array

An array of events who will trigger the hydration. Can contains event names directly or as an array of ['event name', options].

document], ["delay", 5000]], } );">
import lazyHydrate from 'next-lazy-hydrate'

const Card = lazyHydrate(
  () => import("../Card"),
  {
      on: ["visible", ["scroll", () => document], ["delay", 5000]],
  }
);

Support all DOM events and more :

Event name Options Description
all DOM events getTarget: Function who return the event target (default: the wrapped component)
delay delay: Number in ms (default value: 2000) Scheduled hydration.
visible getOptions: Function who return an intersectionObserver options object (default: no options) Requires IntersectionObserver. Polyfill not included. If unsupported the component is directy hydrated.
idle Requires requestIdleCallback. Polyfill not included. If unsupported the component will be hydrated with a delay of 2000ms.

compatibleMode: Boolean (optional, default: false)

Set it to true if your component use Context.

Rule of thumb: If the component render error, turn compatibleMode = true;

whenInputPending: Boolean (optional, default: false)

When set to true use navigator.scheduling.isInputPending to check if there is a pending user input on mount. If that's the case, hydration will be delayed using the strategies defined in the on option to allow the browser to handle the user input. If there is no pending input, the component will be hydrated directly to be interactive as fast as possible.

See https://github.com/WICG/is-input-pending for more infos.

isInputPendingFallbackValue: Boolean (optional, default: true)

The default value returned on browsers who don't implements navigator.scheduling.isInputPending when whenInputPending set to true.

disableFallback: Boolean (optional, default: false)

If set at true the component will not be rendered client side if not rendered server side.

Props

wrapperProps: Object (optional)

Props that are applied to the div which wraps the provided component.

import("../Card"), { on: ["delay"], } ); export default class App extends React.Component { render() { return ( ); } }">
import lazyHydrate from 'next-lazy-hydrate';
import Card from "../Card";

const Card = lazyHydrate(
  () => import("../Card"),
  {
      on: ["delay"],
  }
);

export default class App extends React.Component {
    render() {
        return (
            <Card
                title="my card"
                wrapperProps={{
                    className: "customClassName",
                    style: { display: "contents" },
                }}
            />
        );
    }
}

forceHydration: Boolean (optional, default: false)

Force the hydration of the component.

Explore my project 🤩 : https://thanhle.blog/en/project

You might also like...
Lazy load your component, image or anything matters the performance.

Note This project is now currently maintained by @ameerthehacker, please reach out to him on any issues or help. react-lazyload Lazyload your Componen

Lazy load your component, image or anything matters the performance.

Note This project is now currently maintained by @ameerthehacker, please reach out to him on any issues or help. react-lazyload Lazyload your Componen

⚡️The Fullstack React Framework — built on Next.js
⚡️The Fullstack React Framework — built on Next.js

⚡️The Fullstack React Framework — built on Next.js

⚡️The Fullstack React Framework — built on Next.js — Inspired by Ruby on Rails
⚡️The Fullstack React Framework — built on Next.js — Inspired by Ruby on Rails

⚡️The Fullstack React Framework — built on Next.js — Inspired by Ruby on Rails

React Redux Multi-Step Signup Form. Created with React, Redux Toolkit, and SASS. Plus React Lazy Load for Component loading.
React Redux Multi-Step Signup Form. Created with React, Redux Toolkit, and SASS. Plus React Lazy Load for Component loading.

React Redux Multi-Step Signup Form. Created with React, Redux Toolkit, and SASS. Plus React Lazy Load for Component loading.

🌅 React lazy load images with IntersectionObserver API and Priority Hints
🌅 React lazy load images with IntersectionObserver API and Priority Hints

React Simple Img Smart react lazy load image with IntersectionObserver API, Priority Hints and animations Features Speed up initial page loads by load

React Component to lazy load images and components using a HOC to track window scroll position.
React Component to lazy load images and components using a HOC to track window scroll position.

React Component to lazy load images and other components/elements. Supports IntersectionObserver and includes a HOC to track window scroll position to improve performance.

Lazy load & transition your React images with some WebGL glsl niceness 🎉
Lazy load & transition your React images with some WebGL glsl niceness 🎉

react-gl-transition-image 🎨 Lazy load & transition your React images with some WebGL glsl niceness 🎉 . Easy to use, offers 8 different transitions o

State usage tracking with Proxies. Optimize re-renders for useState/useReducer, React Redux, Zustand and others.

React Tracked State usage tracking with Proxies. Optimize re-renders for useState/useReducer, React Redux, Zustand and others. Documentation site: htt

Performance spy - spy on common libraries and check their performance

Performance Spy How it works It'll override the implentation of your favorite li

A high-performance timer based profiler for React Native that helps you track big performance problems.
A high-performance timer based profiler for React Native that helps you track big performance problems.

Slowlog A high-performance timer for React Native that helps you track big performance problems. Use it as a first line of defense, before tools like

React Native Performance Monitor - Realtime graphing of React Native render performance
React Native Performance Monitor - Realtime graphing of React Native render performance

React Native Performance Monitor This project lets you see a realtime graph of render times within your React Native app. The purpose is for you to be

React hook to clamp multiline text to a given height in a responsive way and with extreme flexibility (under 2.5kb)

use-clamp-text react hook to clamp multiline text to a given height in a responsive way and with extreme flexibility (under 2.5kb) Line Clampin’ (Trun

redux higher order reducer + action to reduce actions under a single subscriber notification

redux-batched-actions Batching action creator and associated higher order reducer for redux that enables batching subscriber notifications for an arra

Declarative React Table under 1kb
Declarative React Table under 1kb

@saltyaom/react-table Declarative React Table under 1kb. Humanity Restored Feature No dependencies. Light, 700 bytes on production. Easy to understand

React Toast Component  - Custom push notification (Toast) implementation under React + stayed by TailwindCSS.
React Toast Component - Custom push notification (Toast) implementation under React + stayed by TailwindCSS.

React Toast Component Online Demo Description This is custom toast component implemented by react hooks + React Context API and stayled using tailwind

A Formik inspired form library that uses MobX under the hood

Formix A Formik inspired form library that uses MobX under the hood and update only the changed fields. Installation Using npm: npm install @euk-labs/

Solana Metaplex AuctionHouse React APP based on CLI code. Code not completely working. Currently under development
Solana Metaplex AuctionHouse React APP based on CLI code. Code not completely working. Currently under development

Solana React Metaplex AuctionHouse UI test ALREADY IN DEVELOPMENT Not all function works correctly This is a simple UI app with TypeScript and Solana

Consuming series data from marvel api and implementing features like infinite scroll, reactive search and lazy loading on images with Angular.

Consuming series data from marvel api and implementing features like infinite scroll, reactive search and lazy loading on images with Angular.

Comments
  • The automated release is failing 🚨

    The automated release is failing 🚨

    :rotating_light: The automated release from the main branch failed. :rotating_light:

    I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

    You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

    Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

    Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

    If you are not sure how to resolve this, here are some links that can help you:

    If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


    No npm token specified.

    An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

    Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


    Good luck with your project ✨

    Your semantic-release bot :package::rocket:

    semantic-release 
    opened by github-actions[bot] 0
  • onClick not firing

    onClick not firing

    Current Behavior

    No onClick event working

    Expected Behavior

    onClick should be firing.

    Steps to Reproduce the Problem

    1. create any component.
    2. import with lazyHydrate
    3. typescript complain with the following:

    'Button' cannot be used as a JSX component. Its element type 'ReactElement<any, any> | Component<ILazyComponentExtended, any, any>' is not a valid JSX element. Type 'Component<ILazyComponentExtended, any, any>' is not assignable to type 'Element | ElementClass'. Type 'Component<ILazyComponentExtended, any, any>' is not assignable to type 'ElementClass'. The types returned by 'render()' are incompatible between these types. Type 'React.ReactNode' is not assignable to type 'import("path/node_modules/@types/hoist-non-react statics/node_modules /@types/react/index").ReactNode'.

    1. when interacting with component, onClick does not fire.

    Environment

    • Version: 1.1.0
    • Platform: Win
    • Node.js Version: v16.15.1
    bug 
    opened by Oumeir-Rengony-Hangar 0
  • No JS works with React 18

    No JS works with React 18

    Current Behavior

    When using lazy hydrate not a single line of js getting executed in component

    Expected Behavior

    JS also should work

    Steps to Reproduce the Problem

    1. create a simple component with something like onHover or onMouseEnter or event an alert in useEffect
    2. use withLazyHydrate
    3. no js will work

    Environment

    • Version: 1.1.0
    • Platform: Mac
    • Node.js Version: 16.16.0
    bug 
    opened by MRezaSafari 2
  • Export withHydrationOnDemand

    Export withHydrationOnDemand

    Feature Request

    Is your feature request related to a problem? Please describe. What if we only want to delay hydration process? (Don't want to dynamic load JS bundle)

    Describe the solution you'd like Export API from withHydrationOnDemand

    Describe alternatives you've considered

    Are you willing to resolve this issue by submitting a Pull Request?

    • [ ] Yes, I have the time, and I know how to start.
    • [ ] Yes, I have the time, but I don't know how to start. I would need guidance.
    • [ ] No, I don't have the time, although I believe I could do it if I had the time...
    • [ ] No, I don't have the time and I wouldn't even know how to start.
    enhancement 
    opened by thanhlmm 0
Releases(v1.1.0)
Owner
Thanh Le
Software Engineer who loves making high-standard products.
Thanh Le
Lazy load your component, image or anything matters the performance.

Note This project is now currently maintained by @ameerthehacker, please reach out to him on any issues or help. react-lazyload Lazyload your Componen

twobin 5.6k Dec 1, 2022
🌅 React lazy load images with IntersectionObserver API and Priority Hints

React Simple Img Smart react lazy load image with IntersectionObserver API, Priority Hints and animations Features Speed up initial page loads by load

Bill 983 Nov 24, 2022
React Component to lazy load images and components using a HOC to track window scroll position.

React Component to lazy load images and other components/elements. Supports IntersectionObserver and includes a HOC to track window scroll position to improve performance.

Albert Juhé Lluveras 1.1k Dec 4, 2022
Lazy load & transition your React images with some WebGL glsl niceness 🎉

react-gl-transition-image ?? Lazy load & transition your React images with some WebGL glsl niceness ?? . Easy to use, offers 8 different transitions o

Jakob Stasilowicz 77 Oct 9, 2022
📶 Improved lazy loading in React with suspense and error boundary

react-with-dynamic About Improved lazy loading in React with suspense and error boundary Demo Basic With Context How to Install First, install the lib

Jakub Biesiada 0 Dec 29, 2021
Tiny (2.3kB) React component for image lazy loading

React Pics Tiny (2.3kB) React component for image lazy loading Demo Table of Contents React Pics Table of Contents Installation Usage Basic With a pla

medipass 32 Dec 26, 2021
Example project to show how to use components lazy loading in ReasonReact

reason-react-lazy-loading Example project to show how to use components lazy loading in ReasonReact. Reason / BuckleScript adaptation from https://med

Javier Chávarri 41 Dec 7, 2021
React components for efficiently rendering large lists and tabular data

React components for efficiently rendering large lists and tabular data. Check out the demo for some examples. Sponsors The following wonderful compan

Brian Vaughn 24.5k Dec 6, 2022
lazysizes is a fast (jank-free), SEO-friendly and self-initializing lazyloader for images

lazysizes is a fast (jank-free), SEO-friendly and self-initializing lazyloader for images (including responsive images picture/srcset), iframes, scripts/widgets and much more. It also prioritizes resources by differentiating between crucial in view and near view elements to make perceived performance even faster.

Alexander Farkas 16.6k Dec 6, 2022
React-lazy-load - Lazy loading in react

React Lazy Load This project is created as part of below YouTube video.

Ashutosh Hathidara 34 Nov 22, 2022