26 July 2022

React hook useEffect is used in functional components to implement life-cycle callbacks. The Effect Hook lets you perform side effects in function components, but some people argue that DOM events might be a better place for that.

Source code viewer
  1. import React, { useState, useEffect } from 'react';
  2.  
  3. export default function App() {
  4. const [windowWidth, setWindowWidth] = useState(window.innerWidth);
  5. const [count, setCount] = useState(() => 0);
  6.  
  7. // Called every time the application renders.
  8. useEffect(() => {
  9. window.console.log('App Render Ran with useEffect');
  10. });
  11. // or simply skip the useEffect hook, this might get called more than once per render
  12. window.console.log('App Render Ran');
  13.  
  14. // Called every time the count changes.
  15. useEffect(() => {
  16. window.console.log('Changed Count: ' + count);
  17. }, [count]);
  18.  
  19. // Runs on mount, because the dependencies never change.
  20. useEffect(() => {
  21. // You can use this to run queries.
  22. window.console.log('onMount event ran');
  23. }, []);
  24.  
  25. // An example of unmount. The return is also called before the effect is executed.
  26. useEffect(() => {
  27. // Unmount is in return of this mount effect.
  28. window.addEventListener('resize', handleResize);
  29. // Return is called on unmount and before effect is executed.
  30. return () => {
  31. // When you want to uso event listeners, you have to remove them on unmount.
  32. window.removeEventListener('resize', handleResize);
  33. };
  34. }, []);
  35.  
  36. const handleResize = () => {
  37. setWindowWidth(window.innerWidth);
  38. };
  39.  
  40. function increaseCount() {
  41. setCount((prevCount) => prevCount + 1);
  42. }
  43.  
  44. return (
  45. <div>
  46. <p>Window width: {windowWidth}px</p>
  47. <p>You clicked {count} times</p>
  48. <button onClick={increaseCount}>
  49. Click me
  50. </button>
  51. </div>
  52. );
  53. }
Programming Language: ECMAScript