https://github.com/tobysmith568/hook-adapter
A lightweight adapter pattern for using React hooks in class components.
https://github.com/tobysmith568/hook-adapter
adapter class-components functional-components hook hooks react
Last synced: 10 months ago
JSON representation
A lightweight adapter pattern for using React hooks in class components.
- Host: GitHub
- URL: https://github.com/tobysmith568/hook-adapter
- Owner: tobysmith568
- License: isc
- Created: 2024-11-13T21:32:45.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-11-29T02:31:26.000Z (over 1 year ago)
- Last Synced: 2024-11-29T03:29:32.620Z (over 1 year ago)
- Topics: adapter, class-components, functional-components, hook, hooks, react
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/hook-adapter
- Size: 75.2 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# hook-adapter
A lightweight adapter pattern for using React hooks in class components.
Useful while transitioning from class components to functional components.
Allows you to wrap blocks of JSX within a class component with the result of a hook.
All hooks are supported, and all hook behaviors like re-renders, state updates, and side effects are preserved.
## Installation
```bash
npm install hook-adapter
```
## Usage
### Hook without parameters
When the hook requires no parameters, you can simply pass the hook function itself to the `hook` prop of the `HookAdapter` component.
The result of the hook is then passed to the children of the `HookAdapter` component via a function children prop.
```jsx
import React, { Component } from "react";
import { HookAdapter } from "hook-adapter";
import { useMyHook } from "./use-my-hook";
export class MyComponent extends Component {
render() {
return (
{hookResult => }
);
}
}
```
### Hooks with parameters
When the hook requires parameters, there are two approaches you can take:
- Wrap the hook in a function that takes no parameters
```jsx
import React, { Component } from "react";
import { HookAdapter } from "hook-adapter";
import { useMyHook } from "./use-my-hook";
export class MyComponent extends Component {
render() {
return (
useMyHook("param1", "param2")}>
{hookResult => }
);
}
}
```
- Pass in the parameters to the `HookAdapter` component via the `parameters` prop
```jsx
import React, { Component } from "react";
import { HookAdapter } from "hook-adapter";
import { useMyHook } from "./use-my-hook";
export class MyComponent extends Component {
render() {
return (
{hookResult => }
);
}
}
```
Both approaches are equivalent and are fully type-safe.
You may find that the latter approach works better with certain linting rules.
## License
hook-adapter is licensed under the [ISC license](./LICENSE.md).