0.2.8 • Published 1 month ago

@tramvai/react-lazy-hydration-render v0.2.8

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
1 month ago

React lazy hydration render

Small library to improve hydration performance in SSR apps. It is based on a lazy hydration approach.

  • Small only 650 bytes (minified and gzipped)
  • Improves TTI do not waste CPU on what the user does not see
  • Customize. component activation mechanism can be changed

More about lazy hydration

Install

npm i --save @tramvai/react-lazy-hydration-render

or

yarn add @tramvai/react-lazy-hydration-render

This library is using IntersectionObserver API. if you need to support older browsers, you should install intersection-observer polyfill in order for it to work.

Usage

Default mode

Component is activated when user scrolls to it.

import React from 'react';
import { LazyRender } from '@tramvai/react-lazy-hydration-render';

const HeavyHeader = () => <header>1</header>;

export const Header = () => (
  <LazyRender>
    <HeavyHeader />
  </LazyRender>
);

Customize wrapper

You can configure the wrapper component.

import React from 'react';
import { LazyRender } from '@tramvai/react-lazy-hydration-render';

const HeavyHeader = () => <header>1</header>;

export const Header = () => (
  <LazyRender wrapper="p" wrapperProps={{ style: { margin: '10px' } }}>
    <HeavyHeader />
  </LazyRender>
);

Configuring IntersectionObserver

import React from 'react';
import { LazyRender, createUseObserverVisible } from '@tramvai/react-lazy-hydration-render';

const useObserverVisible = createUseObserverVisible({
  rootMargin: '0px',
  threshold: 1.0,
});

const HeavyHeader = () => <header>1</header>;

export const Header = () => (
  <LazyRender useObserver={useObserverVisible}>
    <HeavyHeader />
  </LazyRender>
);

Passing custom observer

Package supports changing a loading mechanics. For example, component could be activated on click.

import React, { useEffect, useState } from 'react';
import { LazyRender } from '@tramvai/react-lazy-hydration-render';

const isServer = typeof window === 'undefined';

const useClickActivated = (ref) => {
  const [isVisible, changeVisibility] = useState(isServer);

  useEffect(() => {
    if (!ref.current || isVisible) {
      return;
    }

    ref.current.addEventListener('click', () => changeVisibility(true));
  }, [ref]);

  return isVisible;
};

const HeavyHeader = () => <header>1</header>;

export const Header = () => (
  <LazyRender useObserver={useClickActivated}>
    <HeavyHeader />
  </LazyRender>
);
0.4.1

1 month ago

0.3.0

7 months ago

0.3.1

7 months ago

0.2.8

11 months ago

0.2.7

1 year ago

0.2.6

1 year ago

0.2.5

1 year ago

0.2.4

2 years ago

0.2.3

2 years ago

0.2.2

2 years ago

0.1.31

2 years ago

0.1.30

2 years ago

0.1.29

2 years ago

0.1.28

3 years ago

0.1.27

3 years ago