Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mohebifar/react-use-context-selector
Context selector hook for React
https://github.com/mohebifar/react-use-context-selector
Last synced: 17 days ago
JSON representation
Context selector hook for React
- Host: GitHub
- URL: https://github.com/mohebifar/react-use-context-selector
- Owner: mohebifar
- License: mit
- Created: 2019-12-31T19:34:06.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-05T03:58:41.000Z (almost 2 years ago)
- Last Synced: 2024-10-10T22:15:21.482Z (about 1 month ago)
- Language: TypeScript
- Size: 3.16 MB
- Stars: 31
- Watchers: 4
- Forks: 2
- Open Issues: 26
-
Metadata Files:
- Readme: README.md
- Contributing: .github/CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
README
# react-use-context-selector
Context selector hook for React
## Introduction
There is currently no native way in React to subscribe to a part of context using hooks. That means changing a small part of context, can result in re-rendering every single component that uses the context.
There also exists another package, [use-context-selector](https://github.com/dai-shi/use-context-selector), for the same purpose, but it does not allow you to use the conventional `Consumer` anymore, and it also does not have type declarations.
## Usage
For a working demo, please take a look at [this code sandbox](https://codesandbox.io/s/react-use-context-selector-demo-7p6id)
```
npm install --save react-use-context-selector
``````js
import { createContext } from 'react';
import {
createSelectorProvider,
useContextSelector
} from "react-use-context-selector";const context = createContext({
name: 'Mike',
age: 25,
});
const ProviderWithSelector = createSelectorProvider(context);// Root Component
function Root() {
return (
);
}// The component that consumes the context
function MyComponent() {
// This component will re-render only if the name within the context object change.
const name = useContextSelector(context, value => value.name);return
{name};
}
```