The simplest way for react state management.
All of the popular react state management libs are too complex for me, I only need these:
- Create a state for something;
- Get the value of the state out of react component;
- Set the value of the state out of react component;
- A hook to read the value within react component;
Try usecat if you are like me.
npm install usecat
import { createCat } from 'usecat';
const isLoadingTodosCat = createCat(false);
const todosCat = createCat([]);
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);
}
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 && <div>loading ...</div>}
{todos.map(todo => (
<div key={todo.id}>{todo.title}</div>
))}
</>
)
}
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 && <div>loading ...</div>}
<p>You have {todosCount} todos.</p>
</>
)
}
That's everything.
See how I use usecat in easyy.click and notenote.cc