'Can I change the state for given time and then revert it back to the original state using settimeout
I want to get the value to true for one second, after which it will revert back to false using settimeout but stuck. Here is my code:
const [value, setValue] = useState(false)
const handleClick = () => {
setTimeout(() => {
setValue(!value)
console.log(value);
},1000);
console.log(value);
}
Solution 1:[1]
const [value, setValue] = useState(false);
const timeoutId = useRef(null);
const handleClick = () => {
// clear existing timeout
clearTimeout(timeoutId.current);
// set the value to true
setValue(true);
// revert the value to false after 1s
timeoutId.current = setTimeout(() => setValue(false), 1000);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |