react-state-better
v1.0.1
Published
Better useState hooks, with options for saving previous values
Downloads
3
Readme
React-State-Better
Author: Matan Aviav. E-mail: [email protected] Better useState hooks, with options for saving previous values. Key Features:
- Track previous state
- Track all previous states
How to use?
1. Install the package:
In your project folder, run the following command:
npm install react-state-better
2. Import the package:
Import the hooks in any component you like:
import { useStatePrev, useStateTrack } from 'react-state-better'
3. Use it:
React-State-Better offers 2 hooks:
- useStatePrev
- useStateTrack
useStatePrev:
The useStatePrev hook creates a state and always keep the previous value of it
Parameters:
- value - Any initial value, like in original useState hook.
Returns:
- An array with the following items:
- value - the current value of the state
- setter - a function to modify the state
- prevValue - the previous value of the state
Example:
import { useStatePrev } from 'react-state-better'
function App(){
const [count, setCount, prevCount] = useStatePrev(0)
return (
<div style={{textAlign: 'center'}}>
Count: {count}, PrevCount: {prevCount}<br />
<div>
<button onClick={() => setCount(count+1)}>Increase</button>
<button onClick={() => alert(count)}>Show Count</button>
<button onClick={() => alert(prevCount)}>Show PrevCount</button>
</div>
</div>
)
}
useStateTrack:
The useStateTrack hook creates a state and keeps the changes of it in an array.
Parameters:
- value - Any initial value, like in original useState hook.
Returns:
- An array with the following items:
- value - the current value of the state
- setter - a function to modify the state
- prevValue - the previous value of the state
- changes - an array (stack) with all changes of the state
Example:
import { useStateTrack } from 'react-state-better'
function App(){
const [count, setCount, prevCount, changes] = useStateTrack(0)
return (
<div style={{textAlign: 'center'}}>
Count: {count}, PrevCount: {prevCount}<br />
<div>
<button onClick={() => setCount(count+1)}>Increase</button>
<button onClick={() => alert(count)}>Show Count</button>
<button onClick={() => alert(prevCount)}>Show PrevCount</button>
<button onClick={() => console.log(changes)}>Console.log Changes</button>
</div>
</div>
)
}