react-lazy-value

0.7.0 • Public • Published

react-lazy-value

Lazily evaluate a value during the render phase of your component.

react-lazy-value can be used for data fetching, code splitting, state management, and other async use cases.

Install

npm

npm install react-lazy-value react react-dom

yarn

yarn add react-lazy-value react react-dom

Examples

Data Fetching

import React from "react";
import ReactDOM from "react-dom";
import lazyValue from "react-lazy-value";
 
const currentUser = lazyValue(async () => {
  const response = await fetch(`/api/me`);
  const json = await response.json();
  return json;
});
 
function Loading() {
  return <h1>Loading...</h1>;
}
 
function App() {
  return <h1>Hello {currentUser.value.name}!</h1>;
}
 
ReactDOM.render(
  <React.Suspense fallback={<Loading />}>
    <App />
  </React.Suspense>,
  document.getElementById("app")
);

Code Splitting

import React from "react";
import ReactDOM from "react-dom";
import lazyValue from "react-lazy-value";
 
const moment = lazyValue(() => import("moment"));
 
function Loading(props) {
  return <h1>Loading...</h1>;
}
 
function App() {
  return <h1>{moment.value.calendar()}!</h1>;
}
 
ReactDOM.render(
  <React.Suspense fallback={<Loading />}>
    <App />
  </React.Suspense>,
  document.getElementById("app")
);

Reducer

import lazyValue from "react-lazy-value";
 
function reducer(state, action) {
  switch (action.type) {
    case "LOAD_USER":
      return lazyValue(async () => {
        const response = await fetch(`/api/users/${action.payload.id}`);
        const json = await response.json();
        return json;
      });
 
    case "UPDATE_USER":
      return lazyValue(() => ({
        ...state.value,
        ...action.payload
      }));
 
    default:
      return state;
  }
}

Eager Initialization

import lazyValue from "react-lazy-value";
 
const currentUser = lazyValue.touch(
  lazyValue(async () => {
    const response = await fetch(`/api/me`);
    const json = await response.json();
    return json;
  })
);

How does it work?

Async

react-lazy-value relies on React Suspense when evaluating a promise (or thenable). Suspense lets components “wait” for something before rendering.

JSON.stringify

The lazy object is treated as undefined when in a pending or error state.

Package Sidebar

Install

npm i react-lazy-value

Weekly Downloads

1

Version

0.7.0

License

MIT

Unpacked Size

4.22 kB

Total Files

3

Last publish

Collaborators

  • jomaxx