22 August 2024

To add a delay to updating a string based on state in Preact, you can use the useEffect hook in combination with setTimeout. This allows you to delay the state update by a certain amount of time after the state has changed.

Source code viewer
  1. import { h } from 'preact';
  2. import { useState, useEffect } from 'preact/hooks';
  3.  
  4. function DelayedUpdate() {
  5. const [inputValue, setInputValue] = useState('');
  6. const [delayedValue, setDelayedValue] = useState('');
  7.  
  8. useEffect(() => {
  9. // Set a delay for updating the delayedValue
  10. const timer = setTimeout(() => {
  11. setDelayedValue(inputValue);
  12. }, 1000); // 1000ms = 1 second delay
  13.  
  14. // Cleanup the timeout if the component unmounts or the inputValue changes
  15. return () => clearTimeout(timer);
  16. }, [inputValue]);
  17.  
  18. return (
  19. <div>
  20. <input
  21. type="text"
  22. value={inputValue}
  23. onInput={(e) => setInputValue(e.target.value)}
  24. />
  25. <p>Delayed Value: {delayedValue}</p>
  26. </div>
  27. );
  28. }
  29.  
  30. export default DelayedUpdate;
Programming Language: ECMAScript