{"name":"mobx-react-lite","version":"1.3.1-0","description":"Lightweight React bindings for MobX based on React 16.8 and Hooks","main":"dist/index.js","jsnext:main":"dist/index.module.js","module":"dist/index.module.js","react-native":"dist/native.js","typings":"dist/index.d.ts","types":"dist/index.d.ts","repository":{"type":"git","url":"git+https://github.com/mobxjs/mobx-react-lite.git"},"scripts":{"prettier":"prettier --write \"**/*.js\" \"**/*.ts\"","lint":"tslint --project .","validate":"tsc --noEmit","test":"jest --watch","test:travis":"yarn validate && yarn lint && yarn coverage","coverage":"jest --coverage","prebuild":"rimraf dist","build":"node build-rollup.js"},"author":{"name":"Daniel K."},"license":"MIT","bugs":{"url":"https://github.com/mobxjs/mobx-react-lite/issues"},"homepage":"https://mobxjs.github.io/mobx","peerDependencies":{"mobx":"^4.0.0 || ^5.0.0","react":"^16.8.0"},"devDependencies":{"@types/jest":"24.0.12","@types/node":"11.13.8","@types/react":"16.8.8","@types/react-dom":"16.8.4","coveralls":"3.0.3","husky":"2.1.0","jest":"24.7.1","jest-dom":"3.1.4","jest-environment-jsdom":"24.7.1","jest-mock-console":"0.4.2","lint-staged":"8.1.5","lodash":"4.17.11","mobx":"5.9.4","prettier":"1.17.0","react":"16.8.6","react-dom":"16.8.6","react-test-renderer":"16.8.6","react-testing-library":"7.0.0","react-hooks-testing-library":"0.5.0","rimraf":"2.6.3","rollup":"1.10.1","rollup-plugin-alias":"1.5.1","rollup-plugin-commonjs":"9.3.4","rollup-plugin-filesize":"6.0.1","rollup-plugin-node-resolve":"4.2.3","rollup-plugin-replace":"2.2.0","rollup-plugin-terser":"4.0.4","rollup-plugin-typescript2":"0.21.0","ts-jest":"24.0.2","tslint":"5.16.0","tslint-config-prettier":"1.18.0","typescript":"3.4.5"},"keywords":["mobx","mobservable","react-component","react","reactjs","reactive","hooks","observer","useObserver","useComputer"],"lint-staged":{"*.{ts,js}":["prettier --write","git add"]},"husky":{"hooks":{"pre-commit":"lint-staged"}},"dependencies":{},"readme":"# mobx-react-lite <!-- omit in toc -->\n\n[![Build Status](https://travis-ci.org/mobxjs/mobx-react-lite.svg?branch=master)](https://travis-ci.org/mobxjs/mobx-react-lite)[![Coverage Status](https://coveralls.io/repos/github/mobxjs/mobx-react-lite/badge.svg)](https://coveralls.io/github/mobxjs/mobx-react-lite)\n\n[![Join the chat at https://gitter.im/mobxjs/mobx](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mobxjs/mobx?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n\nThis is a next iteration of [mobx-react](https://github.com/mobxjs/mobx-react) coming from introducing React hooks which simplifies a lot of internal workings of this package.\n\n**You need React version 16.8.0 and above**\n\nClass based components **are not supported** except using `<Observer>` directly in its `render` method. If you want to transition existing projects from classes to hooks (as most of us do), you can use this package alongside the [mobx-react](https://github.com/mobxjs/mobx-react) just fine. The only conflict point is about the `observer` HOC. Subscribe [to this issue](https://github.com/mobxjs/mobx-react/issues/640) for a proper migration guide.\n\n[![NPM](https://nodei.co/npm/mobx-react-lite.png)](https://www.npmjs.com/package/mobx-react-lite)\n\nProject is written in TypeScript and provides type safety out of the box. No Flow Type support is planned at this moment, but feel free to contribute.\n\n-   [API documentation](#api-documentation)\n    -   [`<Observer/>`](#observer)\n    -   [`observer<P>(baseComponent: FunctionComponent<P>, options?: IObserverOptions): FunctionComponent<P>`](#observerpbasecomponent-functioncomponentp-options-iobserveroptions-functioncomponentp)\n    -   [`useObserver<T>(fn: () => T, baseComponentName = \"observed\", options?: IUseObserverOptions): T`](#useobservertfn---t-basecomponentname--%22observed%22-options-iuseobserveroptions-t)\n    -   [`useLocalStore<T>(initializer: () => T): T`](#uselocalstoretinitializer---t-t)\n    -   [`useAsObservableSource<T>(state: T): T`](#useasobservablesourcetstate-t-t)\n    -   [(deprecated) `useObservable<T>(initialValue: T): T`](#useobservabletinitialvalue-t-t)\n        -   [Lazy initialization](#lazy-initialization)\n    -   [(deprecated) `useComputed(func: () => T, inputs: ReadonlyArray<any> = []): T`](#usecomputedfunc---t-inputs-readonlyarrayany---t)\n    -   [(deprecated) `useDisposable<D extends TDisposable>(disposerGenerator: () => D, inputs: ReadonlyArray<any> = []): D`](#usedisposabled-extends-tdisposabledisposergenerator---d-inputs-readonlyarrayany---d)\n-   [Creating MobX reactions inside hook components](#creating-mobx-reactions-inside-hook-components)\n-   [Server Side Rendering with `useStaticRendering`](#server-side-rendering-with-usestaticrendering)\n-   [Why no Provider/inject?](#why-no-providerinject)\n\n## API documentation\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 want to observe only relevant parts of the output for a performance reasons.\n\n```jsx\nimport { Observer, useObservable } from \"mobx-react-lite\"\n\nfunction ObservePerson(props) {\n    const person = useObservable({ name: \"John\" })\n    return (\n        <div>\n            {person.name}\n            <Observer>{() => <div>{person.name}</div>}</Observer>\n            <button onClick={() => (person.name = \"Mike\")}>No! I am Mike</button>\n        </div>\n    )\n}\n```\n\n[![Edit ObservePerson](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/jzj48v2xry?module=%2Fsrc%2FObservePerson.tsx)\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```jsx\nimport { Observer, useObservable } from \"mobx-react-lite\"\n\nfunction ObservePerson(props) {\n    const person = useObservable({ name: \"John\" })\n    return (\n        <div>\n            {person.name}\n            <Observer render={() => <div>{person.name}</div>} />\n            <button onClick={() => (person.name = \"Mike\")}>No! I am Mike</button>\n        </div>\n    )\n}\n```\n\n### `observer<P>(baseComponent: FunctionComponent<P>, options?: IObserverOptions): FunctionComponent<P>`\n\nFunction that converts a function component into a reactive component, which tracks which observables are used automatically re-renders the component when one of these values changes. Observables can be passed through props, accessed from context or created locally with `useObservable`.\n\nAs for options, it is an optional object with the following optional properties:\n\n-   `forwardRef`: pass `true` to use [`forwardRef`](https://reactjs.org/docs/forwarding-refs.html) over the inner component, pass `false` (the default) otherwise.\n\n```tsx\nimport { observer, useObservable } from \"mobx-react-lite\"\n\nconst FriendlyComponent = observer(() => {\n    const friendNameRef = React.useRef()\n    const data = useObservable({\n        friends: [] as string[],\n        addFriend(favorite: boolean = false) {\n            if (favorite === true) {\n                data.friends.unshift(friendNameRef.current.value + \" * \")\n            } else {\n                data.friends.push(friendNameRef.current.value)\n            }\n            friendNameRef.current.value = \"\"\n        },\n        get friendsCount() {\n            return data.friends.length\n        }\n    })\n\n    return (\n        <div>\n            <b>Count of friends: {data.friendsCount} </b>\n            {data.friends.map(friend => (\n                <div>{friend}</div>\n            ))}\n            <hr />\n            <input ref={friendNameRef} />\n            <button onClick={data.addFriend}>Add friend </button>\n            <button onClick={() => data.addFriend(true)}>Add favorite friend</button>\n        </div>\n    )\n})\n```\n\n[![Edit FriendlyComponent](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/jzj48v2xry?module=%2Fsrc%2FFriendlyComponent.tsx)\n\n### `useObserver<T>(fn: () => T, baseComponentName = \"observed\", options?: IUseObserverOptions): T`\n\nLow level implementation used internally by `observer`.\nIt allows you to use an `observer` like behaviour, but still allowing you to optimize the component in any way you want (e.g. using `memo` with a custom `areEqual`, using `forwardRef`, etc.) and to declare exactly the part that is observed (the render phase). One good thing about this is that if any hook changes an observable for some reason then the component won't rerender twice unnecessarily.\n\nThe following optional parameters are available:\n\n-   `baseComponentName`: a string that will be used as part of the reaction name.\n\nAs for the options, the following are available:\n\n-   `useForceUpdate`: optional custom hook that should make a component re-render (or not) when changes are detected.\n\n```tsx\nimport { memo } from \"react\"\nimport { useObserver, useObservable } from \"mobx-react-lite\"\n\nconst Person = memo(props => {\n    const person = useObservable({ name: \"John\" })\n    return useObserver(() => (\n        <div>\n            {person.name}\n            <button onClick={() => (person.name = \"Mike\")}>No! I am Mike</button>\n        </div>\n    ))\n})\n```\n\n### `useLocalStore<T>(initializer: () => T): T`\n\n`useLocalStore` creates a local, observable store that is initialized once, and can be used throughout the life-cycle of the component. Use it if you want to use mobx-powered, local store.\nFor simple cases it is recommended to use `React.setState`, but if your component requires complex view models, consider creating a local mobx store by using this hook.\n\nIf the returned value is a plain object, it will be automatically be passed through `observable`, turning fields into observable properties, and `get` based property accessors in computed values, and functions in bound actions.\n\nIf new class instances are returned from the initializer, they will be kept as is. Quick example:\n\n```typescript\nfunction Counter() {\n    const store = useLocalStore(() => ({\n        count: 0,\n        inc() {\n            this.count += 1\n        }\n    }))\n\n    return useObserver(() => (\n        <div>\n            Count: {store.count}\n            <button onClick={store.inc}>Increment</button>\n        </div>\n    ))\n}\n```\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), the `useLocalStore` should be combined with the `useAsObservableSource` hook, see below.\n\n### `useAsObservableSource<T>(state: T): T`\n\nThe `useAsObservableSource` hook can be used to turn any set of values into an observable object that has a stable reference (the same object is returned every time from the hook).\nThe goal of this hook is to trap React primitives such as props or state into a local, observable object\nso that the `store` initializer can safely refer to it, and get notified if any of the values change.\n\nExample:\n\n```typescript\nfunction Counter({ multiplier }) {\n    const observableProps = useAsObservableSource({ multiplier })\n    const store = useLocalStore(() => ({\n        count: 0,\n        get multiplied() {\n            return observableProps.multiplier * this.count\n        },\n        inc() {\n            this.count += 1\n        }\n    }))\n\n    return (\n        <Observer>\n            {() => (\n                <div>\n                    Multiplied count: {store.multiplied}\n                    <button onClick={store.inc}>Increment</button>\n                </div>\n            )}\n        </Observer>\n    )\n}\n```\n\nIn the above example, any change to `multiplier` prop will show up in the `observableProps` observable object, and be picked up by the `store`.\n\nWarning: _the return value of `useAsObservableSource` should never be deconstructed! So, don't write: `const {multiplier} = useAsObservableSource({ multiplier })`!_\n\nThe value passed to `useAsObservableSource` should always be an object, and is made only shallowly observable.\n\nThe object returned by `useAsObservableSource`, although observable, should be considered read-only for all practical purposes.\nUse `useLocalStore` to create local, observable, mutable, state.\n\nTip: for optimal performance it is recommend to not use `useAsObservableSource` together on the same component as `useObserver` (or `observer`), as it might trigger double renderings. Instead, use `<Observer>`.\n\n# Notice of deprecation\n\nWe will be deprecating following utilities from the package in the next major version. See [the discussion](https://github.com/mobxjs/mobx-react-lite/issues/94) and [the relevant PR](https://github.com/mobxjs/mobx-react-lite/pull/130) for details.\n\n----\n\n### `useObservable<T>(initialValue: T): T`\n\n_Deprecated, will be removed in next major_\n\nReact hook that allows creating observable object within a component body and keeps track of it over renders. Gets all the benefits from [observable objects](https://mobx.js.org/refguide/object.html) including computed properties and methods. You can also use arrays, Map and Set.\n\nWarning: With current implementation you also need to wrap your component to `observer`. It's also possible to have `useObserver` only in case you are not expecting rerender of the whole component.\n\n```tsx\nimport { observer, useObservable, useObserver } from \"mobx-react-lite\"\n\nconst TodoList = () => {\n    const todos = useObservable(new Map<string, boolean>())\n    const todoRef = React.useRef()\n    const addTodo = React.useCallback(() => {\n        todos.set(todoRef.current.value, false)\n        todoRef.current.value = \"\"\n    }, [])\n    const toggleTodo = React.useCallback((todo: string) => {\n        todos.set(todo, !todos.get(todo))\n    }, [])\n\n    return useObserver(() => (\n        <div>\n            {Array.from(todos).map(([todo, done]) => (\n                <div onClick={() => toggleTodo(todo)} key={todo}>\n                    {todo}\n                    {done ? \" ✔\" : \" ⏲\"}\n                </div>\n            ))}\n            <input ref={todoRef} />\n            <button onClick={addTodo}>Add todo</button>\n        </div>\n    ))\n}\n```\n\n#### Lazy initialization\n\nLazy initialization (similar to `React.useState`) is not available. In most cases your observable state should be a plain object which is cheap to create. With `useObserver` the component won't even rerender and state won't be recreated. In case you really want a more complex state or you need to use `observer`, it's very simple to use MobX directly.\n\n```tsx\nimport { observer } from \"mobx-react-lite\"\nimport { observable } from \"mobx\"\nimport { useState } from \"react\"\n\nconst WithComplexState = observer(() => {\n    const [complexState] = useState(() => observable(new HeavyState()))\n    if (complexState.loading) {\n        return <Loading />\n    }\n    return <div>{complexState.heavyName}</div>\n})\n```\n\n[![Edit TodoList](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/jzj48v2xry?module=%2Fsrc%2FTodoList.tsx)\n\nNote that if you want to track a single scalar value (string, number, boolean), you would need [a boxed value](https://mobx.js.org/refguide/boxed.html) which is not recognized by `useObservable`. However, we recommend to just `useState` instead which gives you almost same result (with slightly different API).\n\n### `useComputed(func: () => T, inputs: ReadonlyArray<any> = []): T`\n\n_Deprecated, will be removed in next major_\n\nAnother React hook that simplifies computational logic. It's just a tiny wrapper around [MobX computed](https://mobx.js.org/refguide/computed-decorator.html#-computed-expression-as-function) function that runs computation whenever observable values change. In conjuction with `observer` the component will rerender based on such a change.\n\n```tsx\nconst Calculator = observer(({ hasExploded }: { hasExploded: boolean }) => {\n    const inputRef = React.useRef()\n    const inputs = useObservable([1, 3, 5])\n    const result = useComputed(\n        () => (hasExploded ? \"💣\" : inputs.reduce(multiply, 1) * Number(!hasExploded)),\n        [hasExploded]\n    )\n\n    return (\n        <div>\n            <input ref={inputRef} />\n            <button onClick={() => inputs.push(parseInt(inputRef.current.value) | 1)}>\n                Multiply\n            </button>\n            <div>\n                {inputs.join(\" * \")} = {result}\n            </div>\n        </div>\n    )\n})\n```\n\nNotice that since the computation depends on non-observable value, it has to be passed as a second argument to `useComputed`. There is [React `useMemo`](https://reactjs.org/docs/hooks-reference.html#usememo) behind the scenes and all rules applies here as well except you don't need to specify dependency on observable values.\n\n[![Edit Calculator](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/jzj48v2xry?module=%2Fsrc%2FCalculator.tsx)\n\n### `useDisposable<D extends TDisposable>(disposerGenerator: () => D, inputs: ReadonlyArray<any> = []): D`\n\n_Deprecated, will be removed in next major_\n\nThe disposable is any kind of function that returns another function to be called on a component unmount to clean up used resources. Use MobX related functions like [`reaction`](https://mobx.js.org/refguide/reaction.html), [`autorun`](https://mobx.js.org/refguide/autorun.html), [`when`](https://mobx.js.org/refguide/when.html), [`observe`](https://mobx.js.org/refguide/observe.html), or anything else that returns a disposer.\nReturns the generated disposer for early disposal.\n\nExample (TypeScript):\n\n```typescript\nimport { reaction } from \"mobx\"\nimport { observer, useComputed, useDisposable } from \"mobx-react-lite\"\n\nconst Name = observer((props: { firstName: string; lastName: string }) => {\n    const fullName = useComputed(() => `${props.firstName} ${props.lastName}`, [\n        props.firstName,\n        props.lastName\n    ])\n\n    // when the name changes then send this info to the server\n    useDisposable(() =>\n        reaction(\n            () => fullName,\n            () => {\n                // send this to some server\n            }\n        )\n    )\n\n    // render phase\n    return `Your full name is ${props.firstName} ${props.lastName}`\n})\n```\n\n## Creating MobX reactions inside hook components\n\nIf needed, it is possible to create MobX based side effects in hook based components using the standard APIs. For example:\n\n```typescript\nfunction Counter() {\n    const store = useLocalStore(() => ({\n        count: 0,\n        inc() {\n            store.count += 1\n        }\n    }))\n\n    useEffect(\n        () =>\n            autorun(() => {\n                document.title = \"Ticked: \" + store.count\n            }),\n        []\n    )\n\n    return /* etc */\n}\n```\n\nNote that the disposer function of `autorun` should be returned to `useEffect` so that the effect is cleaned up properly by React.\n\nSecondly, when using MobX based side effects, you typically don't want to re-create them after each rendering, so make sure to pass in an empty array `[]` as deps to `useEffect`.\n\nThis will yield the same limitation as when using `useLocalStore`: changes to props used by the side-effect won't be picked up automatically, so don't refer to them directly. Instead, leverage `useAsObservableSource` again:\n\n```typescript\nfunction Counter({ prefix }) {\n    const observableProps = useAsObservableSource({ prefix })\n    const store = useLocalStore(() => ({\n        count: 0,\n        inc() {\n            store.count += 1\n        }\n    }))\n\n    useEffect(\n        () =>\n            autorun(() => {\n                document.title = `${observableProps.prefix}: ${store.count}`\n            }),\n        []\n    )\n\n    return useObserver(() => (\n        <div>\n            Count: {store.count}\n            <button onClick={store.inc}>Increment</button>\n        </div>\n    ))\n}\n```\n\n## Server Side Rendering with `useStaticRendering`\n\nWhen using server side rendering, 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 `useStaticRendering(true)` when using server side rendering which essentially disables observer.\n\n```js\nimport { useStaticRendering } from \"mobx-react-lite\"\n\nuseStaticRendering(true)\n```\n\nThis makes sure the component won't try to react to any future data changes.\n\n## Why no Provider/inject?\n\nHistorically the Provider was useful because a lot of boilerplate was required due to experimental (but widely used) context. By introducing new [Context API](https://reactjs.org/docs/context.html) in React 16.3 it's fairly easy to do this.\n\n```js\nconst StoreContext = React.createContext(createStore())\n\n// a file with a component\nfunction ConnectedComponent() {\n    // replacement for inject\n    const store = useContext(StoreContext)\n}\n```\n\nIf you need to create a store sometimes later, you can just render `StoreContext.Provider` somewhere in tree.\n\n```js\nconst StoreContext = React.createContext()\n\nfunction App({ children }) {\n    return <StoreContext.Provider value={createStore()}>{children}</StoreContext.Provider>\n}\n```\n","readmeFilename":"README.md","gitHead":"1f0ee0f62b11194fde5f75f191273d2a8dab693a","_id":"mobx-react-lite@1.3.1-0","_npmVersion":"6.4.1","_nodeVersion":"10.12.0","_npmUser":{"name":"fredyc","email":"fredy.c@seznam.cz"},"dist":{"integrity":"sha512-UkP8oDOUSMTCiSlA1QiugILcEvUdp/UXUnbB76ay1x4A/yMtIeKpWv4oDnU1momUFdYfS8ijaOJaD9mvNS/ixg==","shasum":"85ee1a0c49877596da436158b119e7cc93d9dc40","tarball":"http://registry-npm.ywwl.com/mobx-react-lite/download/mobx-react-lite-1.3.1-0.tgz","fileCount":24,"unpackedSize":296485,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcyen3CRA9TVsSAnZWagAAP5kP/1mH26YZrjskBMV9eEev\nN10jLVtKY/69yYMUJqTlgEDWgtrE5zr7CgbYf4FQlTcZxSPZeK5Xx0Nr0Jmr\neCFusbZL4V7mVvGuUCoI9FA+cz7yr94QVoDkA5OvbKi+LVz018Toojkeyu/m\nJ4p+3S2mobzA9UQ8R2g8Jwm0M8xmTVAl+Tpe/ZcfAY8F/yCpOKREld4GZHVC\nUd3pm1InLGxDd6f2L6zSS/ZZRD0IXjy8ACyEkR+V1x+qnY4OMRIeGb4HsOq9\npdeApeXLocNLUiGYILC4DuDW50HCjd16sCPMTEoSmSzCzzYeYWZWlF/NTvtm\nAbdukbdUTATIXnXuAM2lSch0Z44flk8etWckwLB3x/r6dbQnbe88Cm3tjXqJ\no4oguJV43AI46FiQWXPTvmGDLXrLvKfaqKK+BbmIt2PEnY2JFx7R/+pRI0mn\n31JazNuCRzMmtMo93jmWd7E7zoT5LvoneqyGZHHS7DCUCh7/aXAnjPVVD74o\ntWZfMuDHWm6EFgdAC5IFg0NTQYi6N27tRjY3pzOs205hALYD1kMZiA2Yl0QL\nB04Q/gde5Sg3q103k6dUDnE3o8IZK4t2ktYeaBs277CAYqHsWyyCLo1Kn/ij\ndz1Ef+CoQ0etttqTr933SF2eVcx9LjTY1VlnDGmVzZPxyK+FA5Z3/8ofidV7\ngI9N\r\n=+rLP\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIE61Yr2N8/Zr8gfFu6nOiP0JIZ/02ug9B83M2N87twXSAiBKGtX1OLgiuut3Tktmjsbd1A/u/2pjwQ1HLW6Q0K8PhA=="}],"size":98076,"noattachment":false,"key":"/mobx-react-lite/-/mobx-react-lite-1.3.1-0.tgz"},"maintainers":[{"name":"fredyc","email":"fredy.c@seznam.cz"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/mobx-react-lite_1.3.1-0_1556736502483_0.3731287588707599"},"_hasShrinkwrap":false,"publish_time":1556736502682,"_cnpm_publish_time":1556736502682,"dist-tags":{"alpha":"4.0.7-alpha","beta":"3.0.0-beta.1","experimental":"4.0.4-x1","latest":"5.1.2","next":"2.0.0-alpha.5"}}