I'm trying to bring back the magic of setState(value, callback)
from React Class Component days, while adding more functionality on top, like promises and mutable state.
To start using it, initialize it with:
const [state, setState] = useBetterState({
count: 0,
name: '',
});
There are 4 ways to use it while using the updated state right after.
The old way from React Class Components. Why did they get rid of it ? It was soo useful.
setState((i) => {
i.count++;
}, (state) => {
console.log('latest count: ', state.count);
});
AKA: Just change the state. To use the updated value, use state._current
.
state.count++;
console.log('latest count: ', state._current.count);
Async / Await the setState !
let state = await setState((i) => {
i.count++;
});
console.log('latest count: ', state.count);
Classic promise with then callback.
setState((i) => {
i.count++;
}).then((state) => {
console.log('latest count: ', state.count);
});
Just like the old this.setState()
cloned the state object and merged in the new state, this better state does the same.
This means you can change any state without cloning the current state.
setState({ name: 'Andrei' }) // state.count remains the same