{"name":"mobx-react-lite","version":"2.0.0-alpha.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.11","@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.3","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-testing-library":"7.0.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  - [`useObservable<T>(initialValue: T): T`](#useobservabletinitialvalue-t-t)\n    - [Lazy initialization](#lazy-initialization)\n  - [`useComputed(func: () => T, inputs: ReadonlyArray<any> = []): T`](#usecomputedfunc---t-inputs-readonlyarrayany---t)\n  - [`useDisposable<D extends TDisposable>(disposerGenerator: () => D, inputs: ReadonlyArray<any> = []): D`](#usedisposabled-extends-tdisposabledisposergenerator---d-inputs-readonlyarrayany---d)\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# Notice of deprecation\n\nWe are considering deprecation and removal of following utilities from the package. Come join the discussion: https://github.com/mobxjs/mobx-react-lite/issues/94\n\n### `useObservable<T>(initialValue: T): T`\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\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\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## 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":"34b3ba1736144ece7270a628e1460534d93bc947","_id":"mobx-react-lite@2.0.0-alpha.0","_npmVersion":"6.4.1","_nodeVersion":"10.12.0","_npmUser":{"name":"fredyc","email":"fredy.c@seznam.cz"},"dist":{"integrity":"sha512-25et4wJxgQJHVctjMHQ2hQynWH1skSRfMT3UeU9Bf9KqYDPcxfSwt/m6An0KbO8+vyZhZUuKvdSEZx1gcpPYmQ==","shasum":"2e3144deb87d82c800633da04881c4b95f8ea303","tarball":"http://registry-npm.ywwl.com/mobx-react-lite/download/mobx-react-lite-2.0.0-alpha.0.tgz","fileCount":23,"unpackedSize":314232,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcxXwbCRA9TVsSAnZWagAAY64QAKHgDaaplqMbLdBdB+9S\nCQ3IJ0fdqNCaNJbvDV7bjieWNmdO3yBbz/EMQyFTK0xAvsT9MOOzaS7tgeGN\nWL8AojlJr1FubQA3m2Q58DPGZpjf3QxU5ta5+g5jHbrQY4udg8gBdzXSVXxK\n1ARwk7BHqTCnnHNTx1qr1kvKY8bzm32x0/Piu/zP3VpiktBE0BzSjo9CU8Zz\nZARx73VOurP3xSfv1nLJ0TN/8yJEWZBINmTaqCzYe0sIzglu03rJmGjhhD9v\nVsWQt5z8tdjMsvHF+tHLLkppD6DLaj2nWSK763CPGkCX0HFh/aUk+LcCaAnY\nyrrUOI+ItJ0DSFSn1mk6DwcfI3m7qGOnuP2C0Kw0UTPHG1AwN2WDxXgtSV3U\ncg8wQHwcg6bx9HQD2sYB1RI40rYifbZWb3/2dgQQxz6mB+tGkvBRZM3lvddg\ngFQ+OSNLLe/okxJ58KNsIr9xtiXRXvkw/eGIq4XQIxmktbWvLsU0lPtH1voR\ngL4ffQYvHLyyRMxbKAtH/zyz9dr/VyB5rsMZm1BUb9sSVspyuXZOmRyGUNWT\nD0+sdCIfI22YrePdxzQ9l9XkmNNmwgMx7aAbGHFSnzAJcUgM7uWAwDTXI6gX\n+wtZFTusgybitfuAKi5eI8+k0xjMhZwYqdiUIzOHaGU7OufmxQLvmoqTF4lV\n3yjK\r\n=mPxl\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIFATrWcMXedQtmjqc5SH3phIhfFJeyGkiwSXyK/Un5sBAiA0zvu45V9BfBZnJfqqEMqmuM7cNfjEZWe15Yxl6nFtjg=="}],"size":100715,"noattachment":false,"key":"/mobx-react-lite/-/mobx-react-lite-2.0.0-alpha.0.tgz"},"maintainers":[{"name":"fredyc","email":"fredy.c@seznam.cz"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/mobx-react-lite_2.0.0-alpha.0_1556446235050_0.9461159999473367"},"_hasShrinkwrap":false,"publish_time":1556446235292,"_cnpm_publish_time":1556446235292,"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"}}