https://github.com/mdibyo/with-hooks-support
Higher-order component for unlocking React Hooks inside class components
https://github.com/mdibyo/with-hooks-support
higher-order-component hooks hooks-api-react react react-components reacthooks reactjs
Last synced: 8 months ago
JSON representation
Higher-order component for unlocking React Hooks inside class components
- Host: GitHub
- URL: https://github.com/mdibyo/with-hooks-support
- Owner: mDibyo
- Created: 2018-12-21T17:24:24.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2021-08-03T13:16:30.000Z (over 4 years ago)
- Last Synced: 2025-04-17T01:35:35.084Z (8 months ago)
- Topics: higher-order-component, hooks, hooks-api-react, react, react-components, reacthooks, reactjs
- Language: JavaScript
- Homepage:
- Size: 407 KB
- Stars: 4
- Watchers: 1
- Forks: 1
- Open Issues: 15
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# withHooksSupport
[](https://david-dm.org/mDibyo/with-hooks-support)
[](https://www.npmjs.com/package/with-hooks-support)
[](https://www.npmjs.com/package/with-hooks-support)
[](https://opensource.org/licenses/MIT)
[](https://greenkeeper.io/)
Higher-order component for adding hooks support to class components. Check out the
[Code Sandbox Demo](https://codesandbox.io/s/rj85ql72nq).
```jsx
class FancyInput extends React.Component {
render() {
// `useFormInput` returns an object with `value` and `onChange` attributes.
const inputProps = useFormInput();
return ;
}
}
export default withHooksSupport(FancyInput);
```
## Usage
```bash
npm install with-hooks-support
```
Then import
```js
import withHooksSupport from 'with-hooks-support';
```
NOTE: The React Hooks feature is currently only available in certain alpha versions of React.
```bash
npm install react@^16.7.0-alpha.1
```
## Introduction
[React hooks](https://reactjs.org/docs/hooks-intro.html) (introduced in `react@16.7.0-alpha.1`) lets you use
state and other React features without writing a class ie. in functional components. The result is cleaner,
more readable code where the code for a single feature is colocated instead of being spread over several
life-cycle methods.
Now that you have rewritten all your features as custom hooks, how do you use them in your legacy class components?
Using the `withHooksSupport` higher order component, that's how!
Wrap your classes with `withHooksSupport`, and use hooks in the render method without any issues.
```jsx
class ClassComponent extends React.PureComponent {
render() {
const [width, setWidth] = useState(window.innerWidth);
const handleWindowResize = () => setWidth(window.innerWidth);
useEffect(() => {
window.addEventListener('resize', handleWindowResize);
return () => window.removeEventListener('resize', handleWindowResize);
});
return
The window width is {width};
}
}
export default withHooksSupport(ClassComponent);
```
Awesome!