Skip to content

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.

ts
// 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 ​

tsx
import { observer } from 'kr-observable/react';
          
const Component = observer(fc)

Arguments ​

  1. React functional component
  2. 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 ​

tsx
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.

kroman@observable.ru