DEV Community

Luiz Américo
Luiz Américo

Posted on

3

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'
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay