Giter VIP home page Giter VIP logo

react-lazy-hydration's Introduction

React Lazy Hydration

Lazy Hydration for Server Rendered React Components

Installation

npm i react-lazy-hydration

OR

yarn add react-lazy-hydration

Usage

import React from "react";
import LazyHydrate from "react-lazy-hydration";

function App() {
  return (
    <div>
      {/* Skip Hydrating  */}
      <LazyHydrate ssrOnly>
        {...}
      </LazyHydrate>
      {/* Requires IntersectionObserver. Polyfill not included. */}
      <LazyHydrate whenVisible>
        {...}
      </LazyHydrate>
      {/* Requires requestIdleCallback. Polyfill not included. */}
      <LazyHydrate whenIdle>
        {...}
      </LazyHydrate>
      {/* Hydrate on any of the following events */}
      <LazyHydrate on="click" /*OR on={["click","mouseenter",...]} */>
        {...}
      </LazyHydrate>
    </div>
  );
}

Notes

Based on this comment

and heavily adapted from Lazy hydration for Vue SSR

Contribute

First off, thanks for taking the time to contribute! Now, take a moment to be sure your contributions make sense to everyone else.

Reporting Issues

Found a problem? Want a new feature? First of all see if your issue or idea has already been reported. If not, just open a new clear and descriptive issue.

Submitting pull requests

Pull requests are the greatest contributions, so be sure they are focused in scope, and do avoid unrelated commits.

react-lazy-hydration's People

Contributors

dependabot[bot] avatar hadeeb avatar pmdamora avatar rjyo avatar sarink avatar scriptedalchemy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-lazy-hydration's Issues

Not working on starter NextJS app

I have tried to use this wrapper component as shown in the README.

But I am not experiencing any difference of functionality, am I missing something?

I expected ssrOnly to render a component with zero functionality. But it is being rendered full and interactive.

I have also tried the other events and am seeing no difference.

Example code:

import LazyHydrate from 'react-lazy-hydration'

export default function Test() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
      Hello Test!
      <LazyHydrate ssrOnly>
        <div
          style={{ background: 'red', width: 300, height: 300 }}
          onClick={() => console.log('clicked')}
        >
          Click Me
        </div>
      </LazyHydrate>
    </div>
  )
}

I am seeing clicked in the console with this code after clicking.

Export multiple components

Consider exporting multiple components for different hydration strategies as opposed to a single component controlled with props.

Pros

  • Smaller size (assuming an app does not need/use all these strategies).
  • Opens up possibilities to further enhance/customise each strategy(like #13)

Cons

Support rootMargin on intersectionObserver

Some components can load in a janky fashion if they are hydrated when directly in view.

Id like to propose the ability to add a rootMargin, allowing a component to hydrate itself before a user is fully viewing it.

Use case:

  • carousels where additional computation is required after mounting
  • components that use fade-in effects or lazyloading images does not have a smooth experience
  • components that use intersection observer themselves

Reasoning

Would provide a better UX

Feature suggestion: an onInteraction parameter

I am on a project with a largish page, I found that waiting for the the user to interact with the DOM, a hover or a touch, before hydrating these elements greatly improved Time To Interactive. Google has a time window after idle where it listens for blocking and I believe onIdle triggers fast enough that Google bots see that as blocking interactivity.

I can/have done the above with the promise but wonder if a PR with onInteraction would be appreciated.

Not working with Next 9

I've added this to my project which used Next v9 for server-side rendering.
I get this error :

LayoutEffect should only be used in components that render exclusively on the client. See https://fb.me/react-uselayouteffect-ssr for common fixes.
    in Unknown (at Header.js:7)
    in header (at Header.js:5)
    in Header (at page.js:15)
    in div (at PageContainer.js:12)
    in PageContainer (at page.js:14)
    in Context.Provider (at PageContext.js:28)
    in PageProvider (at page.js:10)
    in Page (at DefaultPage.js:22)
    in DefaultPage
    in withRouter(DefaultPage) (at pages/index.js:27)
    in Index
    in Query
    in Apollo(Index)
    in Context.Provider
    in Context.Consumer
    in ApolloProvider
    in withApollo(Apollo(Index))
    in App
    in Context.Provider
    in Context.Provider
    in Context.Provider
    in Context.Provider
    in AppContainer
    in AppTree
    in Context.Provider

and this one client side :

    at e (index.m.js:1)
    at commitHookEffectList (react-dom.development.js:19980)
    at commitPassiveHookEffects (react-dom.development.js:20015)
    at HTMLUnknownElement.callCallback (react-dom.development.js:347)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:397)
    at invokeGuardedCallback (react-dom.development.js:454)
    at flushPassiveEffectsImpl (react-dom.development.js:22868)
    at unstable_runWithPriority (scheduler.development.js:643)
    at runWithPriority$2 (react-dom.development.js:11305)
    at flushPassiveEffects (react-dom.development.js:22841)
    at react-dom.development.js:22419
    at scheduler_flushTaskAtPriority_Normal (scheduler.development.js:436)
    at flushTask (scheduler.development.js:482)
    at flushWork (scheduler.development.js:607)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:231) ```

Is this compatible with Next.js?

hydration not working in Ms Edge or IE11

...i guess because it uses display:contents which is not supported in these browsers

I tried a css hack

div[style*="contents"] {
        display: block !important;
       }

but the hydration still failed.

Feature Suggestion - Custom wrapper element

Hi,

Great work with this project ๐Ÿ‘

I wondered if it would be possible to include the ability to specify a custom wrapper element?

By default it could be a div (so it isn't a breaking change) but an additional wrapper attribute could be available to allow spans, articles, etc?

Flicker/layout shift with dynamic imports - Next.js

I'm following this guide from @ScriptedAlchemy (also on Stack Overflow) to implement lazy hydration in my SSG Next.js app.

It works, except the HTML of any dynamic import (using next/dynamic) gets destroyed during hydration. This causes flickering and huge layout shifts on larger websites.

The flicker/shift doesn't occur when directly importing a component using import - but then lazy hydration becomes redundant, because the component's JS is bundled with the initial page load.

Here's a link to a reproduction.

Any help would be greatly appreciated. I'm hoping to use this technique on a number of high-traffic websites. Lighthouse performance scores are up ~10-15 points and initial page load size is down over 50% for the site I'm testing it on.

`noWrapper` prop isn't used

Not sure if this lib is still being maintained as there hasn't been much activity in a while but i've come across an issue when using the noWrapper prop.

When doing something like:

<LazyHydrate whenIdle noWrapper="nav">
    /* ...complex component ... */
</LazyHydrate>

the tag specified in noWrapper is ignored and just the children are returned.

I've put together an example repo here: https://codesandbox.io/s/strange-napier-6tvbp4?file=/src/App.tsx

From a quick look over the code, my guess is it has something to do with the if statement on line 168:

if (noWrapper) {
return children;
}

It looks like that's checking whether noWrapper exists rather than whether its actual value is true...

if (noWrapper) { // here noWrapper could be string or true
  return children; 
}

but the problem may be deeper than that.

VM9:85 ReferenceError: cleanup is not defined

Hello, I am using Next 12, I am using react-lazy-hydration this way:

<LazyHydrate ...> <Component /> </LazyHydrate>

When I use whenVisible or whenIdle, I have the following error when serving the website statically (I don't see the error when running in dev ):

image

I don't see the error when using ssrOnly option.

Cypress tests fail for hydrated components

Here is a reproducible repo: https://github.com/justman00/react-lazy-hydration-cypress. When running yarn e2e and selecting the only available test, observe how the tests fail. I found a workaround of how to fix them is to give display: contents; to the child container, see https://github.com/justman00/react-lazy-hydration-cypress/blob/main/components/MyLayout.js#L9. I would like to understand what would cause it to fail and why it is being fixed by another wrapper with the mentioned above styles.

pass click event to component

Is it possible to forward event further down to component In case when on="click" option is used? It would make hydration of interactive components so much more usable.

It is mostly important for mobile, as we have "mouseenter" on desktop which, probably, would fire before user has time to click. On mobile, "cilck" (or "tap") would often be the first event page ever gets and we can't waste it

Expected behaviour:

  1. user clicks
  2. component is hydrated
  3. component handles "click" event

Anchor Links (to other pages) get disrupted when

I am using this package together with gatsby and got a nice perfomance boost.

Unfortunately anchor links get disrupted when you use lazy hidration on a page. Specifically anchor links to other pages, not same page anchor links.

Anyone got any idea what could cause this or how to fix it?

Issue Intersection Observer not defined

We have a problem with this line on some browsers that we are crashing with this exception:
Can't find variable: IntersectionObserver Safari 14.1 on WebMobile
IntersectionObserver is not defined Chrome 49 on Desktop

We can change it to typeof IntersectionObserver !== 'undefined' or window.IntersectionObserver
Can we make a PR with this change?
Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.