1.0.1 • Published 9 months ago

react-state-better v1.0.1

Weekly downloads
-
License
LICENSE IN LICENS...
Repository
github
Last release
9 months ago

React-State-Better

Author: Matan Aviav. E-mail: matanaviav.npmjs@gmail.com 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: 1. useStatePrev 2. 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>
  )
}
1.0.1

9 months ago

1.0.0

9 months ago