10 August 2024

When using useState in Preact (or React), the setState function doesn't accept a callback as a second parameter, unlike in some other libraries. Instead, the proper way to execute code after a state update is to use the useEffect hook, which reacts to changes in state.

Source code viewer
  1. import { h } from 'preact';
  2. import { useState, useEffect, useLayoutEffect } from 'preact/hooks';
  3.  
  4. const MyComponent = () => {
  5. const [count, setCount] = useState(0);
  6.  
  7. // useEffect will run after the state change has been committed to the DOM
  8. useEffect(() => {
  9. console.log(`useEffect: Count has been updated to: ${count}`);
  10. }, [count]);
  11.  
  12. // useLayoutEffect will run synchronously after the DOM has been updated but before the browser has painted
  13. useLayoutEffect(() => {
  14. console.log(`useLayoutEffect: Count has been updated to: ${count}`);
  15. }, [count]);
  16.  
  17. return (
  18. <div>
  19. <p>Count: {count}</p>
  20. <button onClick={() => setCount(count + 1)}>Increment</button>
  21. </div>
  22. );
  23. };
  24.  
  25. export default MyComponent;
Programming Language: ECMAScript