25 July 2022

useState is a hook what you use in a React function to create a state variable. This is not used if you use React class components. useState has tricks you must know about.

Source code viewer
  1. import React, { useState } from 'react';
  2.  
  3. function Example() {
  4. // useState hook. Declare a new state variable, in the top level only. Called every time on render.
  5. const [count, setCount] = useState(0);
  6. // The default value is run only once. Not on every render.
  7. const [count, setCount] = useState(() => 0);
  8. // Object as a value of state.
  9. const [objState, setObjState] = useState({ count: 0, name: 'Object State' });
  10.  
  11. function increaseCount() {
  12. // Can't run more than once.
  13. setCount(count + 1);
  14. // Can run multiple times, this is a better way to set state.
  15. setCount((prevCount) => prevCount + 1);
  16. // Setting object values doesn't merge the values automatically, so this code will delete name property of our object.
  17. setCount((prevObjState) => { count: prevObjState.count + 1 });
  18. // Correct way to update object.
  19. setCount((prevObjState) => { ...prevObjState, count: prevObjState.count + 1 });
  20. }
  21.  
  22. return (
  23. <div>
  24. <p>You clicked {count} times</p>
  25. <button onClick={increaseCount}>
  26. Click me
  27. </button>
  28. </div>
  29. );
  30. }
Programming Language: ECMAScript