@bemedev/hook-wrapper
v1.0.0
Published
Wrapper of hooks to render them in a component without recreating them.
Readme
@bemedev/hook-wrapper
A lightweight utility to wrap React hooks and render them in a dedicated wrapper component. This isolates hook-driven updates, preventing unnecessary parent component rerenders and optimizing React application performance.
Why use @bemedev/hook-wrapper?
In standard React development, calling a hook inside a parent component causes the entire parent component (and all its children) to rerender whenever the hook's state changes.
By wrapping a custom hook with wrap or useHook, you create a wrapper component
that:
- Calls the hook internally.
- Accepts hook arguments as props.
- Exposes a
renderprop to display the UI, localizing hook rerenders to the render callback rather than triggering a parent-level update.
See how it works here
Installation
pnpm add @bemedev/hook-wrapper
# or
npm install @bemedev/hook-wrapper
# or
yarn add @bemedev/hook-wrapperUsage Example
1. Define a Custom Hook
import { useState } from 'react';
export const useCounter = ({ step = 1 }: { step?: number } = {}) => {
const [count, setCount] = useState(0);
return { count, inc: () => setCount(c => c + step) };
};2. Wrap the Hook and Render It
import { wrap } from '@bemedev/hook-wrapper';
import { useCounter } from './useCounter';
// Wrap the hook to get a wrapper component
const CounterWrapper = wrap(useCounter);
export const Demo = () => {
// The parent component (Demo) will render only ONCE.
// Clicking the increment button will only rerender the children inside the CounterWrapper.
return (
<div>
<h3>Parent Component (No Rerenders on Hook Change)</h3>
<CounterWrapper
step={5}
render={({ count, inc }) => (
<div>
<p>Count: {count}</p>
<button onClick={inc}>Increment by 5</button>
</div>
)}
/>
</div>
);
};API Reference
wrap(hook) / useHook(hook)
Wraps a custom hook and returns a component that renders it (useHook is an alias of
wrap).
Parameters
hook: The React hook function to wrap.
Returns
A React component that accepts:
- Props matching the arguments of the wrapped hook.
- A
renderfunction prop that receives the hook's return value and returns a React element.
wrap.noParams(hook, render)
Helper for wrapping hooks that accept no parameters. Returns a component function directly without requiring props at render time.
Parameters
hook: The parameterless React hook function to wrap.render: A function receiving the hook's return value and returning a React element.
Returns
A parameterless React component function () => ReactNode.
License
MIT
Changelog
Read CHANGELOG.md for more details about the changes.
Author
chlbri ([email protected])
