The simplest react state manager.
npm install usecat
npm install usecat
`
Usage
$3
`
import { createCat } from 'usecat';
const isLoadingTodosCat = createCat(false);
const todosCat = createCat([]);
`
$3
`
import { isLoadingTodosCat, todosCat } from './cats';
async function fetchTodos() {
const currentTodos = todosCat.get();
if (currentTodos?.length) {
return;
}
isLoadingTodosCat.set(true);
try {
const response = await fetch('your-fancy-api');
const todos = await response.json();
todosCat.set(todos);
} catch (e) {
// handle error ;)
}
isLoadingTodosCat.set(false);
}
`
$3
`
import { useCat } from 'usecat';
import { isLoadingTodosCat, todosCat } from './cats'
import { fetchTodos } from './network';
function MyComponent() {
const isLoading = useCat(isLoadingTodosCat);
const todos = useCat(todosCat);
useEffect(() => {
fetchTodos();
}, [])
return (
<>
{isLoading && loading ...}
{todos.map(todo => (
{todo.title}
))}
>
)
}
`
You can also provide a selector, if the selected value is not changed, it won't trigger re-rendering:
`
import { useCat } from 'usecat';
import { isLoadingTodosCat, todosCat } from './cats'
import { fetchTodos } from './network';
function MyComponent() {
const isLoading = useCat(isLoadingTodosCat);
const todosCount = useCat(todosCat, todos => todos?.length || 0);
useEffect(() => {
fetchTodos();
}, [])
return (
<>
{isLoading && loading ...}
You have {todosCount} todos.
>
)
}
``