Integration with React β
Observable comes with a built-in observer
HOC for React.
observer β
WARNING
As of version 3.0.0
, the observer
has been moved to the /react
subdirectory.
// Before (versions < 3.0.0)
import { observer } from 'kr-observable'
// After (versions β₯ 3.0.0)
import { observer } from 'kr-observable/react'
The observer
utility wraps a React component and makes it reactive by automatically tracking observables used during rendering. When any of those observables change, the component re-renders.
Since observer is built on the same reactivity system as autorun, it benefits from the same optimizations β like dependency tracking and batching updates. This means applications using Observable are highly optimized by default, and you typically wonβt need to add manual checks like React.memo or useCallback to prevent unnecessary renders.
WARNING
observer
can only be used with functional components.
Syntax β
import { observer } from 'kr-observable/react';
const Component = observer(fc)
Arguments β
- React functional component
- An optional
Boolean
flag that when is true enables logging. Observable will print to console info about each render/re-render including reasons.TIP
Avoid using arrow functions with observer, that will make logs more readable.
Return value β
React functional component
Example β
import { observer } from 'kr-observable/react';
const ListItem = observer(function listItem({ post }) {
return (
<div>{post.title}</div>
)
})
Tips β
TIP
observer
is also well tested with Preact/compat.