{"name":"mobx-react","version":"9.2.1","keywords":["mobx","mobservable","react-component","react","reactjs","reactive"],"author":{"name":"Michel Weststrate"},"license":"MIT","_id":"mobx-react@9.2.1","maintainers":[{"name":"fredyc","email":"fredy.c@seznam.cz"},{"name":"mweststrate","email":"mweststrate@gmail.com"},{"name":"eshenbrener","email":"strate@yandex.ru"},{"name":"andykog","email":"mail@andykog.com"}],"homepage":"https://mobx.js.org","bugs":{"url":"https://github.com/mobxjs/mobx/issues"},"dist":{"shasum":"19b1036442d2515eeb6f5fbb2c9c770d81c32f80","tarball":"http://registry-npm.ywwl.com/mobx-react/download/mobx-react-9.2.1.tgz","fileCount":47,"integrity":"sha512-WJNNm0FB2n0Z0u+jS1QHmmWyV8l2WiAj8V8I/96kbUEN2YbYCoKW+hbbqKKRUBqElu0llxM7nWKehvRIkhBVJw==","signatures":[{"sig":"MEUCIQDLTiETDRtDP7fXPKggQujuD7N6I3oXuLPlR6VZHBCceAIgNC/n+530c43GyxfdntAULnQvvEqXj3IJbnvdBWYyOKQ=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":650246,"size":169969,"noattachment":false,"key":"/mobx-react/-/mobx-react-9.2.1.tgz"},"main":"dist/index.js","types":"dist/index.d.ts","unpkg":"dist/mobxreact.umd.production.min.js","module":"dist/mobxreact.esm.js","source":"src/index.ts","funding":{"url":"https://opencollective.com/mobx","type":"opencollective"},"gitHead":"989de2d198e7a15c1fc1b981e1a96e50083ff2a0","scripts":{"lint":"eslint src/**/* --ext .js,.ts,.tsx","test":"jest","build":"node ../../scripts/build.js mobxReact","test:size":"yarn import-size --report . observer","build:test":"yarn build --target test","test:check":"yarn test:types","test:types":"tsc --noEmit","prepublishOnly":"yarn build --target publish"},"typings":"dist/index.d.ts","_npmUser":{"name":"mweststrate","email":"mweststrate@gmail.com"},"jsdelivr":"dist/mobxreact.umd.production.min.js","umd:main":"dist/mobxreact.umd.production.min.js","repository":{"url":"git+https://github.com/mobxjs/mobx.git","type":"git"},"_npmVersion":"10.9.3","description":"React bindings for MobX. Create fully reactive components.","directories":{},"jsnext:main":"dist/mobxreact.esm.js","sideEffects":false,"_nodeVersion":"22.19.0","dependencies":{"mobx-react-lite":"^4.1.1"},"react-native":"dist/mobxreact.esm.js","_hasShrinkwrap":false,"devDependencies":{"mobx":"^6.15.0","expose-gc":"^1.0.0","mobx-react-lite":"^4.1.1"},"peerDependencies":{"mobx":"^6.9.0","react":"^16.8.0 || ^17 || ^18 || ^19"},"peerDependenciesMeta":{"react-dom":{"optional":true},"react-native":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/mobx-react_9.2.1_1758895549458_0.05718312692838223","host":"s3://npm-registry-packages-npm-production"},"readme":"# mobx-react\n\n[![CircleCI](https://circleci.com/gh/mobxjs/mobx-react.svg?style=svg)](https://circleci.com/gh/mobxjs/mobx-react)\n[![CDNJS](https://img.shields.io/cdnjs/v/mobx-react.svg)](https://cdnjs.com/libraries/mobx-react)\n[![Minzipped size](https://img.shields.io/bundlephobia/minzip/mobx-react.svg)](https://bundlephobia.com/result?p=mobx-react)\n[![Discuss on Github](https://img.shields.io/badge/discuss%20on-GitHub-orange)](https://github.com/mobxjs/mobx/discussions)\n[![View changelog](https://img.shields.io/badge/changelogs.xyz-Explore%20Changelog-brightgreen)](https://changelogs.xyz/mobx-react)\n\nPackage with React component wrapper for combining React with MobX.\nExports the `observer` decorator and other utilities.\nFor documentation, see the [MobX](https://mobx.js.org) project.\nThis package supports both React and React Native.\n\n## Compatibility matrix\n\nOnly the latest version is actively maintained. If you're missing a fix or a feature in older version, consider upgrading or using [patch-package](https://www.npmjs.com/package/patch-package)\n\n| NPM Version | Support MobX version | Supported React versions | Added support for:                                                               |\n| ----------- | -------------------- | ------------------------ | -------------------------------------------------------------------------------- |\n| v10         | 7.\\*                 | >=18                     | MobX 7, Hooks, React 18 strict mode                                              |\n| v9          | 6.\\*                 | >16.8                    | Hooks, React 18.2 in strict mode                                                 |\n| v7          | 6.\\*                 | >16.8 < 18.2             | Hooks                                                                            |\n| v6          | 4.\\* / 5.\\*          | >16.8 <17                | Hooks                                                                            |\n| v5          | 4.\\* / 5.\\*          | >0.13 <17                | No, but it is possible to use `<Observer>` sections inside hook based components |\n\n`mobx-react` is a wrapper around `mobx-react-lite` for applications that also need class component support:\n\n-   Support for function components through `mobx-react-lite`\n-   Support for class based components for `observer` and `@observer`\n\n## Installation\n\n`npm install mobx-react`\n\nOr CDN: https://unpkg.com/mobx-react (UMD namespace: `mobxReact`)\n\n```javascript\nimport { observer } from \"mobx-react\"\n```\n\nThis package provides the bindings for MobX and React.\nSee the [official documentation](https://mobx.js.org/react-integration.html) for how to get started.\n\nUse `React.createContext` to pass stores around.\n\n## API documentation\n\nPlease check [mobx.js.org](https://mobx.js.org/) for the general documentation. The documentation below highlights some specifics.\n\n### `observer(component)`\n\nFunction (and decorator) that converts a React component definition, React component class, or stand-alone render function, into a reactive component. A converted component will track which observables are used by its effective `render` and automatically re-render the component when one of these values changes.\n\n#### Functional Components\n\n`React.memo` is automatically applied to functional components provided to `observer`. `observer` does not accept a functional component already wrapped in `React.memo`, or an `observer`, in order to avoid consequences that might arise as a result of wrapping it twice.\n\n#### Class Components\n\n`shouldComponentUpdate` is not supported. As such, it is recommended that class components extend `React.PureComponent`. The `observer` will automatically patch non-pure class components with an internal implementation of `React.PureComponent` if necessary.\n\nExtending `observer` class components is not supported. Always apply `observer` only on the last class in the inheritance chain.\n\nSee the [MobX](https://mobx.js.org/react-integration.html#react-integration) documentation for more details.\n\n```javascript\nimport { observer } from \"mobx-react\"\n\n// ---- ES6 syntax ----\nconst TodoView = observer(\n    class TodoView extends React.Component {\n        render() {\n            return <div>{this.props.todo.title}</div>\n        }\n    }\n)\n\n// ---- ESNext syntax with decorator syntax enabled ----\n@observer\nclass TodoView extends React.Component {\n    render() {\n        return <div>{this.props.todo.title}</div>\n    }\n}\n\n// ---- or just use function components: ----\nconst TodoView = observer(({ todo }) => <div>{todo.title}</div>)\n```\n\n##### Note on using props and state in derivations\n\n`mobx-react` version 6 and lower would automatically turn `this.state` and `this.props` into observables.\nThis has the benefit that computed properties and reactions were able to observe those.\nHowever, since this pattern is fundamentally incompatible with `StrictMode` in React 18.2 and higher, this behavior has been removed in React 18.\n\nAs a result, we recommend to no longer mark properties as `@computed` in observer components if they depend on `this.state` or `this.props`.\n\n```javascript\n@observer\nclass Doubler extends React.Component<{ counter: number }> {\n    @computed // BROKEN! <-- @computed should be removed in mobx-react > 7\n    get doubleValue() {\n        // Changes to this.props will no longer be detected properly, to fix it,\n        // remove the @computed annotation.\n        return this.props * 2\n    }\n\n    render() {\n        return <div>{this.doubleValue}</div>\n    }\n}\n```\n\nSimilarly, reactions will no longer respond to `this.state` / `this.props`. This can be overcome by creating an observable copy:\n\n```javascript\n@observer\nclass Alerter extends React.Component<{ counter: number }> {\n    @observable observableCounter: number\n    reactionDisposer\n\n    constructor(props) {\n        this.observableCounter = counter\n    }\n\n    componentDidMount() {\n        // set up a reaction, by observing the observable,\n        // rather than the prop which is non-reactive:\n        this.reactionDisposer = autorun(() => {\n            if (this.observableCounter > 10) {\n                alert(\"Reached 10!\")\n            }\n        })\n    }\n\n    componentDidUpdate() {\n        // sync the observable from props\n        this.observableCounter = this.props.counter\n    }\n\n    componentWillUnmount() {\n        this.reactionDisposer()\n    }\n\n    render() {\n        return <div>{this.props.counter}</div>\n    }\n}\n```\n\nMobX-react will try to detect cases where `this.props`, `this.state` or `this.context` are used by any other derivation than the `render` method of the owning component and throw.\nThis is to make sure that neither computed properties, nor reactions, nor other components accidentally rely on those fields to be reactive.\n\nThis includes cases where a render callback is passed to a child, that will read from the props or state of a parent component.\nAs a result, passing a function that might later read a property of a parent in a reactive context will throw as well.\nInstead, when using a callback function that is being passed to an `observer` based child, the capture should be captured locally first:\n\n```javascript\n@observer\nclass ChildWrapper extends React.Component<{ counter: number }> {\n    render() {\n        // Collapsible is an observer component that should respond to this.counter,\n        // if it is expanded\n\n        // BAD:\n        return <Collapsible onRenderContent={() => <h1>{this.props.counter}</h1>} />\n\n        // GOOD: (causes to pass down a fresh callback whenever counter changes,\n        // that doesn't depend on its parents props)\n        const counter = this.props.counter\n        return <Collapsible onRenderContent={() => <h1>{counter}</h1>} />\n    }\n}\n```\n\n### `Observer`\n\n`Observer` is a React component, which applies `observer` to an anonymous region in your component.\nIt takes as children a single, argumentless function which should return exactly one React component.\nThe rendering in the function will be tracked and automatically re-rendered when needed.\nThis can come in handy when needing to pass render function to external components (for example the React Native listview), or if you\ndislike the `observer` decorator / function.\n\n```javascript\nclass App extends React.Component {\n    render() {\n        return (\n            <div>\n                {this.props.person.name}\n                <Observer>{() => <div>{this.props.person.name}</div>}</Observer>\n            </div>\n        )\n    }\n}\n\nconst person = observable({ name: \"John\" })\n\nReactDOM.render(<App person={person} />, document.body)\nperson.name = \"Mike\" // will cause the Observer region to re-render\n```\n\nIn case you are a fan of render props, you can use that instead of children. Be advised, that you cannot use both approaches at once, children have a precedence.\nExample\n\n```javascript\nclass App extends React.Component {\n    render() {\n        return (\n            <div>\n                {this.props.person.name}\n                <Observer render={() => <div>{this.props.person.name}</div>} />\n            </div>\n        )\n    }\n}\n\nconst person = observable({ name: \"John\" })\n\nReactDOM.render(<App person={person} />, document.body)\nperson.name = \"Mike\" // will cause the Observer region to re-render\n```\n\n### `useLocalObservable` hook\n\nLocal observable state can be introduced by using the `useLocalObservable` hook, that runs once to create an observable store. A quick example would be:\n\n```javascript\nimport { useLocalObservable, Observer } from \"mobx-react\"\n\nconst Todo = () => {\n    const todo = useLocalObservable(() => ({\n        title: \"Test\",\n        done: true,\n        toggle() {\n            this.done = !this.done\n        }\n    }))\n\n    return (\n        <Observer>\n            {() => (\n                <h1 onClick={todo.toggle}>\n                    {todo.title} {todo.done ? \"[DONE]\" : \"[OPEN]\"}\n                </h1>\n            )}\n        </Observer>\n    )\n}\n```\n\nWhen using `useLocalObservable`, all properties of the returned object will be made observable automatically, getters will be turned into computed properties, and methods will be bound to the store and apply mobx transactions automatically. If new class instances are returned from the initializer, they will be kept as is.\n\nIt is important to realize that the store is created only once! It is not possible to specify dependencies to force re-creation, _nor should you directly be referring to props for the initializer function_, as changes in those won't propagate.\n\nInstead, if your store needs to refer to props (or `useState` based local state), sync those values into the store with `useEffect`.\n\nNote that in many cases it is possible to extract the initializer function to a function outside the component definition. Which makes it possible to test the store itself in a more straight-forward manner, and avoids creating the initializer closure on each re-render.\n\n_Note: using `useLocalObservable` is mostly beneficial for really complex local state, or to obtain more uniform code base. Note that using a local store might conflict with future React features like concurrent rendering._\n\n### Server Side Rendering with `enableStaticRendering`\n\nWhen using server side rendering, normal lifecycle hooks of React components are not fired, as the components are rendered only once.\nSince components are never unmounted, `observer` components would in this case leak memory when being rendered server side.\nTo avoid leaking memory, call `enableStaticRendering(true)` when using server side rendering.\n\n```javascript\nimport { enableStaticRendering } from \"mobx-react\"\n\nenableStaticRendering(true)\n```\n\nThis makes sure the component won't try to react to any future data changes.\n\n### Which components should be marked with `observer`?\n\nThe simple rule of thumb is: _all components that render observable data_.\nIf you don't want to mark a component as observer, for example to reduce the dependencies of a generic component package, make sure you only pass it plain data.\n\n### Enabling decorators (optional)\n\nDecorators are currently a stage-2 ESNext feature. How to enable them is documented [here](https://mobx.js.org/enabling-decorators.html#enabling-decorators-).\n\n### Should I still use smart and dumb components?\n\nSee this [thread](https://www.reddit.com/r/reactjs/comments/4vnxg5/free_eggheadio_course_learn_mobx_react_in_30/d61oh0l).\nTL;DR: the conceptual distinction makes a lot of sense when using MobX as well, but use `observer` on all components.\n\n## DevTools\n\n`mobx-react@6` and higher are no longer compatible with the mobx-react-devtools.\nThat is, the MobX react devtools will no longer show render timings or dependency trees of the component.\nThe reason is that the standard React devtools are also capable of highlighting re-rendering components.\nAnd the dependency tree of a component can now be inspected by the standard devtools as well, as shown in the image below:\n\n![hooks.png](hooks.png)\n\n## FAQ\n\n**Should I use `observer` for each component?**\n\nYou should use `observer` on every component that displays observable data.\nEven the small ones. `observer` allows components to render independently from their parent and in general this means that\nthe more you use `observer`, the better the performance become.\nThe overhead of `observer` itself is negligible.\nSee also [Do child components need `@observer`?](https://github.com/mobxjs/mobx/issues/101)\n\n**I see React warnings about `forceUpdate` / `setState` from React**\n\nThe following warning will appear if you trigger a re-rendering between instantiating and rendering a component:\n\n```\n\nWarning: forceUpdate(...): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.`\n\n```\n\n-- or --\n\n```\n\nWarning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.\n\n```\n\nUsually this means that (another) component is trying to modify observables used by this components in their `constructor` or `getInitialState` methods.\nThis violates the React Lifecycle, `componentWillMount` should be used instead if state needs to be modified before mounting.\n","publish_time":1758895549700,"_cnpm_publish_time":1758895549700,"dist-tags":{"latest":"10.0.3"}}