Fast state that can be shared across components outside of the React tree.
Fast updates are achieved by letting React reconcile only specific components where you use the value.
Inspired by the idea from Recoil - state subscriptions (atoms) minus all the rest. Just a state value one can share and have components hook into it without updating the entire subtree.
import { createValueContainer, useValue } from "react-nano-state";
// Value container can be exported and reused in any part of the tree.
const searchContainer = createValueContainer("Type the search");
const SearchInput = () => {
// All we need to subscribe to those sharable value changes.
const [search, setSearch] = useValue(searchContainer);
const onChange = (event) => {
setSearch(event.target.value);
};
return <input onChange={onChange} value={value} />;
};
A value container is an object that can be shared across the code base and used to subscribe to the value.
// value-containers.js
import { createValueContainer } from "react-nano-state";
export const searchContainer = createValueContainer(initialValue);
It is very similar to React's useState
with the difference that you access a shared state.
import { useValue } from "react-nano-state";
import { searchContainer } from "./value-containers";
const SearchInput = () => {
const [search, setSearch] = useValue(searchContainer);
const onChange = (event) => {
setSearch(event.target.value);
};
return <input onChange={onChange} value={search} />;
};
You can update the value outside of React components and components using it will receive the update.
import { searchContainer } from "./value-containers";
searchContainer.dispatch(newSearch);
You can install and bundle this package using any tool you like. This repo will not add any code to support a particular way of installing or bundling, because it is using a standard ECMAScript and the tools you are using should know how to deal with it.