Skip to content

mDibyo/with-hooks-support

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

64 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

withHooksSupport

dependencies min minzip License: MIT Greenkeeper badge

Higher-order component for adding hooks support to class components. Check out the Code Sandbox Demo.

class FancyInput extends React.Component {
  render() {
    // `useFormInput` returns an object with `value` and `onChange` attributes.
    const inputProps = useFormInput();

    return <input {...inputProps} />;
  }
}

export default withHooksSupport(FancyInput);

Usage

npm install with-hooks-support

Then import

import withHooksSupport from 'with-hooks-support';

NOTE: The React Hooks feature is currently only available in certain alpha versions of React.

npm install react@^16.7.0-alpha.1

Introduction

React hooks (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.

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 <div>The window width is {width}</div>;
  }
}

export default withHooksSupport(ClassComponent);

Awesome!