Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/liximomo/use-closure
React hook for capture up-to-date value in closure.
https://github.com/liximomo/use-closure
Last synced: about 2 months ago
JSON representation
React hook for capture up-to-date value in closure.
- Host: GitHub
- URL: https://github.com/liximomo/use-closure
- Owner: liximomo
- License: mit
- Created: 2019-02-26T10:17:38.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2022-12-08T14:41:48.000Z (about 2 years ago)
- Last Synced: 2024-10-31T18:32:20.535Z (about 2 months ago)
- Language: TypeScript
- Size: 869 KB
- Stars: 3
- Watchers: 3
- Forks: 0
- Open Issues: 24
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: code-of-conduct.md
Awesome Lists containing this project
README
# useClosure
React hook for capture up-to-date value in closure.
## What problem dose the library solve?
Becasue how closure works in javascript. The variables in the parent scope will not change throngh a closure's liefcycle. See the example:```js
import React, { useState, useEffect, useCallback } from 'react';function Counter() {
const [count, setCount] = useState(1);
// useCallBack will return a memoized version of the callback to prevent unnecessary renders
const onClickChild = useCallback(() =>
// Nooo! `count` will always be 1
console.log('current', count);
});useEffect(() => {
window.
const handler = setInterval(() => {
setCount(count => count + 1);
}, 1000 * 1);return () => {
clearInterval(handler);
};
}, []);return (
count: {count}
);
}
```How can we solve this? Meet [useClosure](#usage);
## Install
```
npm install use-closure --save
```or
```
yarn add use-closure
```## Usage
```js
import React, { useState, useEffect } from 'react';
import useClosure from 'use-closure';function Counter() {
const [count, setCount] = useState(1);// useClosure always return the same reference, so the Child component will never re-render.
const onClickChild = useClosure(() =>
// Yesss! `count` will always be the current value
console.log('current', count);
});useEffect(() => {
window.
const handler = setInterval(() => {
setCount(count => count + 1);
}, 1000 * 1);return () => {
clearInterval(handler);
};
}, []);return (
count: {count}
);
}
```