atoms-react
v1.0.8
Published
react-atom - A mini state management library for React
Downloads
14
Readme
atoms-react ·
atoms-react is A mini state management library for React.
Demo: https://codesandbox.io/s/jovial-cookies-fdw2r
Installation
npm install atoms-react
Or if you're using yarn:
yarn add atoms-react
Example
import React, { memo } from 'react';
import { atom, useAtom, selectAtom } from 'atoms-react';
const countAtom = atom(0);
const baseAtom = atom({ text: 'text!!!', des: 'des!!!' });
const sliceAtom = selectAtom(
baseAtom,
(value) => value.text,
(pre, next) => pre === next,
);
const Child = memo(() => {
const [value, update] = useAtom(countAtom);
return (
<>
<p>I'm Child: {value}</p>
<button
onClick={() => {
update(value + 1);
}}
>
Child: +1
</button>
</>
);
});
export default memo(() => {
const [value, setValue] = useAtom(countAtom);
return (
<div>
<p>I'm Father: {value}</p>
<button onClick={() => setValue(value + 1)}>Father: +1</button>
<Child />
</div>
);
});
for react library
A Provider
will be necessary if we need to hold different atom values for different component trees.
Provider
commonly used with library.
import React from 'react';
import { atom, useAtom, Provider } from 'atoms-react';
const countAtom = atom(0);
const DemoComponent = memo(() => {
const [value, setValue] = useAtom(countAtom);
return (
<>{value}</>
);
});
const Wrapper = (Component: typeof DemoComponent) => (props: any) => (
<Provider>
<Component {...props} />
</Provider>
);
export default Wrapper(DemoComponent);
License
atoms-react is MIT licensed.