Integration with React β
Observable comes with a built-in binding for React through an observer
Higher-Order Component.
observer β
The observer()
HOC 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.
Syntax β
import { observer } from 'kr-observable/react';
const Component = observer(component, debug?: boolean);
Arguments β
- React component
- An optional
Boolean
flag that when is true enables debug mode.
Debug mode provides detailed console logging showing:- Which observables were read during render
- When component will re-render
- What changes triggered re-render
- When a component is disposed
Avoid anonymous functions
For more readable debug logs, use named functions (e.g., function ListItem()) instead of anonymous arrow functions. This ensures your component has a clear name in React DevTools and debug outputs.
Return value β
React component
Example β
import { makeObservable } from 'kr-observable';
import { observer } from 'kr-observable/react';
// Create an observable state
const appState = makeObservable({
count: 0,
increase() {
++this.count;
},
decrease() {
--this.count;
},
});
function Counter() {
return (
<div>
<button onClick={appState.decrease}>-</button>
<div>{appState.count}</div>
<button onClick={appState.increase}>+</button>
</div>
);
}
// Wrap and export the component
export default observer(Counter);
// or with debug mode enabled
//export default observer(Counter, true);