DEV Community

Luiz Américo
Luiz Américo

Posted on

From React to Web Components: using hooks (part 2)

This is a follow up to the evaluation of hooks usage with web components using Haunted library.

Using third party (React) hooks

The use of third party React hook libraries is possible because Haunted provides an API with same signature as React. With some bundling setup is possible to make the library load Haunted instead of React.

Webpack can be configured as below:

module.exports = {
  resolve: {
    alias: {
      react: 'haunted'
    }
  }
}

To see if it works in practice, i converted this demo which depends on react-media-hook. The end result is here.

The code related to hooks worked flawlessly without any adaptation. Most of the conversion work was due to differences between React and web components concepts.

This approach (package alias using bundler) will not work if the project itself uses React or if the hook library relies on JSX / Virtual DOM.

An interoperability tale

The converted demo uses @stencil/router, a web component based router with an API similar to React Router. It is built with StencilJS, a component compiler featuring JSX, virtual dom, decorators etc.

It uses also wc-fontawesome, the web component version of React FontAwesome, built on top of RawElement which extends LitElement base class.

All working together. A demonstration of how web components built with different technology can work together.

Conclusion

It's feasible to work with Hooks using web components and take advantage of most of third party libraries. Haunted worked glitch free in the experiences i did, proving be a valuable tool.

Whether Hooks is better than classes for web components development is a matter of debate. Sure, is ergonomic, composable etc but, personally, i will still prefer, for the time being, classes due to ability to use (upcoming) decorators syntax and better attributes support.

All in all, it does not need to be one or other. Even in same project both approaches can coexist, allowing developer to choose the technology that better suits each situation.

Top comments (0)