Security News
PyPI’s New Archival Feature Closes a Major Security Gap
PyPI now allows maintainers to archive projects, improving security and helping users make informed decisions about their dependencies.
mobx-react-lite
Advanced tools
mobx-react-lite is a lightweight wrapper around MobX that provides React bindings for functional components. It allows you to use MobX for state management in your React applications with minimal boilerplate and high performance.
Observer Component
The `observer` function is used to create a reactive component that will automatically re-render when the observed state changes. In this example, the `Counter` component re-renders whenever `counter.count` is updated.
import React from 'react';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
const counter = observable({ count: 0 });
const Counter = observer(() => (
<div>
<button onClick={() => counter.count++}>Increment</button>
<p>{counter.count}</p>
</div>
));
export default Counter;
Using MobX stores
This example demonstrates how to use MobX stores with `mobx-react-lite`. The `CounterStore` class is an observable store, and the `Counter` component observes changes to the store and re-renders accordingly.
import React from 'react';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
class CounterStore {
@observable count = 0;
increment() {
this.count++;
}
}
const counterStore = new CounterStore();
const Counter = observer(() => (
<div>
<button onClick={() => counterStore.increment()}>Increment</button>
<p>{counterStore.count}</p>
</div>
));
export default Counter;
Using hooks with MobX
The `useLocalObservable` hook allows you to create local observable state within a functional component. This example shows how to use the hook to create a local counter state and update it within the component.
import React from 'react';
import { observer, useLocalObservable } from 'mobx-react-lite';
const Counter = observer(() => {
const counter = useLocalObservable(() => ({ count: 0, increment() { this.count++; } }));
return (
<div>
<button onClick={counter.increment}>Increment</button>
<p>{counter.count}</p>
</div>
);
});
export default Counter;
Redux is a popular state management library for JavaScript applications. Unlike MobX, which uses observables and reactive programming, Redux relies on a unidirectional data flow and immutable state updates. Redux is often used with React through the `react-redux` bindings.
Recoil is a state management library for React that provides a set of utilities for managing state in a more granular and efficient way. It uses atoms and selectors to manage state and derive computed values. Recoil is designed to work seamlessly with React's concurrent mode.
Zustand is a small, fast, and scalable state management library for React. It uses hooks to manage state and provides a simple API for creating and updating state. Zustand is less opinionated than MobX and can be a good choice for simpler state management needs.
This is a next iteration of mobx-react coming from introducing React hooks which simplifies a lot of internal workings of this package. Class based components are not supported except using <Observer>
directly in its render
method.
You need React version 16.7.0-alpha.0 which is highly experimental and not recommended for a production.
Project 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.
Function 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
.
import { observer, useObservable } from "mobx-react-lite"
const FriendlyComponent = observer(() => {
const friendNameRef = React.useRef()
const data = useObservable({
friends: [] as string[],
addFriend(favorite: boolean = false) {
if (favorite === true) {
data.friends.unshift(friendNameRef.current.value + " * ")
} else {
data.friends.push(friendNameRef.current.value)
}
friendNameRef.current.value = ""
},
get friendsCount() {
return data.friends.length
}
})
return (
<div>
<b>Count of friends: {data.friendsCount} </b>
{data.friends.map(friend => (
<div>{friend}</div>
))}
<hr />
<input ref={friendNameRef} />
<button onClick={data.addFriend}>Add friend </button>
<button onClick={() => data.addFriend(true)}>Add favorite friend</button>
</div>
)
})
Observer
Observer
is a React component, which applies observer
to an anonymous region in your component.
It takes as children a single, argumentless function which should return exactly one React component.
The rendering in the function will be tracked and automatically re-rendered when needed.
This can come in handy when needing to pass render function to external components (for example the React Native listview), or if you
dislike the observer
function.
import { Observer } from "mobx-react-lite"
function ObservePerson(props) {
const person = useObservable({ name: "John" })
return (
<div>
{person.name}
<Observer>{() => <div>{person.name}</div>}</Observer>
<button onClick={() => (person.name = "Mike")}>No! I am Mike</button>
</div>
)
}
In 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. Example
import { Observer } from "mobx-react-lite"
function ObservePerson(props) {
const person = useObservable({ name: "John" })
return (
<div>
{person.name}
<Observer render={() => <div>{person.name}</div>} />
<button onClick={() => (person.name = "Mike")}>No! I am Mike</button>
</div>
)
}
useStaticRendering
When using server side rendering, the components are rendered only once.
Since components are never unmounted, observer
components would in this case leak memory when being rendered server side.
To avoid leaking memory, call useStaticRendering(true)
when using server side rendering which essentially disables observer.
import { useStaticRendering } from "mobx-react-lite"
useStaticRendering(true)
This makes sure the component won't try to react to any future data changes.
Historically the Provider was useful because a lot of boilerplate was required due to experimental (but widely used) context. By introducing new Context API in React 16.3 it's fairly easy to do this.
const StoreContext = React.createContext(createStore())
// a file with a component
function ConnectedComponent() {
// replacement for inject
const store = useContext(StoreContext)
}
If you need to create a store sometimes later, you can just render StoreContext.Provider
somewhere in tree.
const StoreContext = React.createContext()
function App({ children }) {
return <StoreContext.Provider value={createStore()}>{children}</StoreContext.Provider>
}
// a file with a component
function ConnectedComponent() {
// replacement for inject
const store = useContext(StoreContext)
}
FAQs
Lightweight React bindings for MobX based on React 16.8+ and Hooks
The npm package mobx-react-lite receives a total of 1,110,961 weekly downloads. As such, mobx-react-lite popularity was classified as popular.
We found that mobx-react-lite demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now allows maintainers to archive projects, improving security and helping users make informed decisions about their dependencies.
Research
Security News
Malicious npm package postcss-optimizer delivers BeaverTail malware, targeting developer systems; similarities to past campaigns suggest a North Korean connection.
Security News
CISA's KEV data is now on GitHub, offering easier access, API integration, commit history tracking, and automated updates for security teams and researchers.