Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Preact signals are far superior to other state management patterns for react, but don't use a ContextProvider as shown is this article, pass the signals as props instead.

e.g:

  function MyComponent({ disabled }: { disabled: Signal<boolean> }) {
    // ...
  }


Both approaches are valid and applicable in different circumstances. To extend your example further, you often end up needing to do:

  function MySubComponent({ disabled }: { disabled: Signal<boolean> }) {
    // ...
  }  

  function MyComponent({ disabled }: { disabled: Signal<boolean> }) {
    return <MySubComponent disabled={disabled} />
  }
passing the value on and on as you go down a component chain. Context lets you avoid all that.

Where signals offer an important benefit is in localizing re-rendering. If you use context with regular, non-signal values the entire VDOM tree has to be re-rendered when the context value changes (because there's no way to know what code depends on its value). With signals you can change the value of a signal in the context without changing the context itself, meaning that the only part of the VDOM tree that gets re-rendered is the one using the signal.

With performance considerations out of the way context becomes a really interesting way to provide component composition without having to specify the same props over and over as you make your way down a chain.


ContextProvider is for when you have some data that any random component might need, and you don’t want to clutter up the system by passing it through every component (this is called “prop drilling”). Or maybe you can’t pass it through some container component that you don’t control.

That consideration is orthogonal to what the useful data is. It could be a signal, or not. In other words, signals are not an alternative to context.


Could you explain why?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: