withHook
DEPRECATED: The with-hook package is deprecated.
Consider using the with-hooks-support package instead, which has a cleaner and more intuitive API for allowing hooks inside class components.
Unlock React Hooks inside class components.
Component { // `useFormInput` returns an object with `value` and `onChange` attributes. const WithFormInput = ; return <WithFormInput> <input /> </WithFormInput> ; }
Check out the Code Sandbox Demo!
Usage
npm install with-hook
Then import
;
Introduction
React hooks (introduced in react@17.0.0-alpha
) 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 hooks, how do you use them in your legacy class components?
Using the withHook
higher order component, that's how!
Consider the following functional component:
{ const width setWidth = ; const handleWindowResize = ; ; return <div>The window width is width</div>;}
We can add the same hooks code to our class component:
PureComponent { const WithWindowWidth = ; return <WithWindowWidth> <div>The window width is width</div></WithWindowWidth> ; }
Now if we were to refactor all our hooks code into a custom hook
{ const width setWidth = ; const handleWindowResize = ; ; return width;}
We can write our components like so:
{ const width = ; return <div>The window width is width</div>;} PureComponent { const WithWindowWidth = ; return <WithWindowWidth> <div>The window width is width</div> </WithWindowWidth> ; }
Special case: Hooks that don't return a value
Now, suppose you don't care about the return value for a hook. The child to the hook component can be a normal component instead of a render function.
Component { ; thistextareaRef = React; } { const WithAutosizing = ; return <WithAutosizing> <textarea = /> <WithAutosizing> ; }
Awesome!