matthewp / haunted

React's Hooks API implemented for web components 👻
BSD 2-Clause "Simplified" License
2.58k stars 92 forks source link

feat: new hook useProvideContext #452

Open cristinecula opened 1 year ago

cristinecula commented 1 year ago

This hook enables you to provide values to one or multiple contexts from the same component.

Instead of nesting multiple Provider elements:

<app-state-provider .value=${appState}>
  <settings-provider .value=${settings}>
    <main-app></main-app>
  </settings-provider>
</app-state-provider>

you can do all of it in the same component hook:

useProvideContext(AppStateContext, appState, [appState]);
useProvideContext(SettingsContext, settings, [settings]);
changeset-bot[bot] commented 1 year ago

🦋 Changeset detected

Latest commit: 23b754151901874c046cee3e181519b352f57dbe

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package | Name | Type | | ------- | ----- | | haunted | Minor |

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

netlify[bot] commented 1 year ago

Deploy Preview for hauntedhooks ready!

Name Link
Latest commit 23b754151901874c046cee3e181519b352f57dbe
Latest deploy log https://app.netlify.com/sites/hauntedhooks/deploys/636500be564c3b0009b5c0c1
Deploy Preview https://deploy-preview-452--hauntedhooks.netlify.app
Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site settings.

cristinecula commented 1 year ago

@bennypowers this code duplicates a lot of the code from the Provider in makeContext. The Provider component could be rewritten as:

Provider = component(({value}) => useProvideContext(Context, value), {useShadowDOM: false})

Do you think that would be a good idea?

bennypowers commented 1 year ago

will these interop with @lit-labs/context or vanilla context protocol elements?

cristinecula commented 1 year ago

I don't know. This PR is just re-implementing the existing haunted Context Provider as a hook.

matthewp commented 1 year ago

We need to at some point have a conversation on how to add features to Haunted without unnecessarily increasingly the bundle size. Like, this feature seems useful but a large number of projects will never need context. Does it make sense to make this kind of thing available via import 'haunted/context' instead?

cristinecula commented 1 year ago

@matthewp isn't this already mitigated by the fact that you're publishing the package as an es6 library? I think most bundlers will tree-shake the context if it's not used at all. In any case, import "haunted/context" sounds good.