useUndoState
Aboutβ
Drop in replacement for useState hook but with undo functionality.
Installationβ
npm install --save rooks
Importing the hookβ
import { useUndoState } from 'rooks';
Usageβ
const Demo = () => {
const [value, setValue, undo] = useUndoState(0);
return (
<div>
<span>Current value: {value}</span>
<button onClick={() => setValue(value + 1)}>Increment</button>
<button onClick={undo}>Undo</button>
</div>
);
};
render(<Demo />);
You can pass any kind of value to hook just like React's own useState.
const Demo = () => {
const [value, setValue, undo] = useUndoState({ data: 42 });
return (
<div>
<span>Current value: {value}</span>
<button onClick={() => setValue({ data: value.data + 1 })}>
Increment object data
</button>
<button onClick={undo}>Undo</button>
</div>
);
};
render(<Demo />);
Setter function can also be used with callback just like React's own useState.
const [value, setValue, undo] = useUndoState({ data: 42 })
() => setValue(current => current + 1)
const Demo = () => {
const [value, setValue, undo] = useUndoState(0);
return (
<div>
<span>Current value: {value}</span>
<button onClick={() => setValue((current) => current + 1)}>
Increment
</button>
<button onClick={undo}>Undo</button>
</div>
);
};
render(<Demo />);
To preserve memory you can limit number of steps that will be preserved in undo history.
const [value, setValue, undo] = useUndoState(0, { maxSize: 30 });
// now when calling undo only last 30 changes to the value will be preserved
Argumentsβ
Arguments | Type | Description | Default value |
---|---|---|---|
initialValue | boolean | Initial value of the state | false |
Options | Object | An options object for the hook | {maxSize: 100} |
Note: The second argument is an options object which currently accepts a maxSize which governs the maximum number of previous states to keep track of.
Returned array itemsβ
Returned Array items | Type | Description |
---|---|---|
value | Any | Current value |
setValue | function | Setter function to update value |
undo | function | Undo state value |
Codesandbox Exampleβ
Basic usageβ
Join Bhargav's discord serverβ
You can click on the floating discord icon at the bottom right of the screen and talk to us in our server.