https://github.com/mskelton/lazy-context
A thin layer on top of React context that supports "lazy subscription" to only re-render when the data you care about changes.
https://github.com/mskelton/lazy-context
lazy react react-context
Last synced: about 2 months ago
JSON representation
A thin layer on top of React context that supports "lazy subscription" to only re-render when the data you care about changes.
- Host: GitHub
- URL: https://github.com/mskelton/lazy-context
- Owner: mskelton
- License: isc
- Created: 2023-10-22T02:44:40.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2024-02-17T02:53:46.000Z (about 2 years ago)
- Last Synced: 2024-10-18T08:17:47.014Z (over 1 year ago)
- Topics: lazy, react, react-context
- Language: TypeScript
- Homepage: https://npm.im/lazy-context
- Size: 485 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# Lazy Context
[](https://github.com/mskelton/npm-template/actions)
[](https://www.npmjs.com/package/lazy-context)
A thin layer on top of React context that supports "lazy subscription" to only
re-render when the data you care about changes.
## Installation
**npm**
```bash
npm install lazy-context
```
**Yarn**
```bash
yarn add lazy-context
```
**pnpm**
```bash
pnpm add lazy-context
```
**bun**
```bash
bun add lazy-context
```
## How does it work?
One of the challenges with React context is that it's all or nothing when you
update. If you have an object with ten properties and a child component only
needs one of those properties, React will still re-render the child if any of
the other nine properties change. In most cases this is fine, but when fine
tuning performance where ever re-render matters, it starts to break down.
That's where React Lazy Context comes in. It will observe which keys you use
from the context object and only re-render the component when those specific
keys change, ignoring unrelated updates.
## Example Usage
```javascript
import React, { memo } from "react"
import { createLazyContext } from "lazy-context"
const [useUserContext, UserContextProvider] = createLazyContext({
name: "Mark Skelton",
hobbies: [],
})
// UserCard will only re-render when `name` changes. Changes to `hobbies` will
// not trigger a re-render.
const UserCard = memo(function UserCard() {
const { name } = useUserContext()
return
{name}
})
function Page({ children }) {
return (
{children}
)
}
```