use-constant-handler
v0.1.9
Published
react hooks useConstant ans useHandler
Downloads
8
Maintainers
Readme
use-constant-handler
React hooks for make constant pointer to function/handler
Usage
import { useConstHandler } from "use-constant-handler";
const Component = ({ onEvent, onInit }) => {
// pointer to onInit callback can changed, but pointor to initHandler don't change
const onInitHandler = useConstFunc(() => onInit());
useEffect(() => {
onInitHandler();
}, [onInitHandler]); //it will call only once becouse initHandler don`t change
// We do not need redraw input when onEvent callback change.
// New onEvent callback need only when SubComponent call onEvent.
// Pointer to onChange callback can changed,
// but pointor to onChangeHandler don't change
const onEventHandler = useConstHandler((e) => onEvent(e))
return <SubComponent onEvent={onEventHandler}/>;
}
Description
Source code of useConstFunc:
const useConstFunc = (f) => {
const { current } = useRef((...args) => current[FUNC_KEY]?.(...args));
current[FUNC_KEY] = f;
return current;
};
Source code of useConstHandler:
const useConstHandler = (f) => {
const { current } = useRef((...args) => (current[FUNC_KEY] ?? f)(...args));
useLayoutEffect(() => {
current[FUNC_KEY] = f;
});
return current;
};