How to use Observables like useState in React? #121
Unanswered
AradSharafi
asked this question in
Q&A
Replies: 1 comment 2 replies
-
See https://legendapp.com/open-source/state/react-basics/#two-ways-to-re-render-on-state-changes You can make the component an observer to re-render when any tracked observable changes, or const Component = observer(function Component() {
const num$ = useObservable(0)
const num = num$.get()
return (
<>
<button onClick={() => num$.set(value => value + 1)}>Add</button>
<div>Num: {num}</div>
</>
)
}) |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I want to use Observables in React to create a state that behaves like the useState hook. Specifically, I sometimes have a state that I want to turn into an Observable. How can I make an Observable work like a state?
I have tried using an Observable in a component, but when it changes, the component does not update. To handle this, I have been using the useSelector hook in the component to re-render as useState. Is this a good approach, or is there a better way to handle this situation?
Beta Was this translation helpful? Give feedback.
All reactions