I've the following component:
import React, { useEffect, useState } from 'react';
const UndoInput = () => {
const [name, setName] = useState('');
return(
<div className = 'Name'>
<input
onChange = {(e) => setName(e.target.value)}
value = {name}>
</input>
<Undo
name = {name}
setName = {setName}
/>
</div>
);
}
export default UndoInput;
The <Undo/>
component is a buffer storing the value of an input on every change, allowing to perform an undo action.
const Undo = ({name, setName}) => {
const [buffer, setBuffer] = useState(['', '', '']);
const [index, setIndex] = useState(-1);
useEffect(() => {
let copy = [...buffer, name].slice(-3);
let pos = index + 1;
if(pos > 2)
pos = 2;
setBuffer(copy);
setIndex(pos);
}, [name]);
const undo = () => {
let pos = index - 1;
if(pos < 0)
pos = -1;
setName(buffer[pos]);
setIndex(pos);
}
return(
<button onClick = {undo}>Undo</button>
);
}
Example:
If a user types 'abc' on the input, buffer = ['a', 'ab', 'abc']
and index = 2
.
When a user clicks on the button, the component should go back to the previous state. That means, buffer = ['a', 'ab', 'abc']
and index = 1
.
After clicking on the button, setName(buffer[pos])
is executed, the useEffect()
is retriggered: buffer = ['ab', 'abc', 'ab']
and index = 2
(not desired).
How can I prevent to retrigger the useEffect()
Hook, iff it was retriggered by the undo()
function?
<Undo />
component approach and just use a custom hookuseUndoableState
?