0.0.2 • Published 7 years ago
react-use-bound-callback-hook v0.0.2
react-use-bound-callback-hook
A useBoundCallback hook for React. Similar to useCallback but binds the arguments instead of relying on closures.
What it does:
- Memoizes a callback function based on arguments array and context passed
- If callback function is not previously bound, binds it to passed in arguments and context
- If callback function is previously bound, checks if passed in arguments and context differ from last bound ones.
- If they differ, rebinds and returns rebound callback.
- Else returns previously bound callback.
Installation
yarn add react-use-bound-callback-hooknpm install react-use-bound-callback-hookUsage:
import { useBoundCallback } from 'react-use-bound-callback-hook';
function onChange(setText, ev) {
setText(ev.currentValue.text);
};
function SomeComponent(props) {
const [text, setText] = useState('');
return (
<input type="text" onChange={useBoundCallback(onChange, [setText])} />
);
}useBoundCallback takes three arguments:
callback- The callback function to be memoizedarguments- The arguments to be bound to the callback functioncontext- The context to execute the callback function as i.e. the value ofthisinside the callback. Optional. Defaultnull.