Skip to content

Latest commit

 

History

History
36 lines (27 loc) · 763 Bytes

pass-a-function-to-a-usestate-updater.md

File metadata and controls

36 lines (27 loc) · 763 Bytes

Pass A Function To A useState Updater

Let's say you have a component with a toggle state:

const [toggle, setToggle] = useState(false);

You can change the state of the toggle by directly passing a value to setToggle.

setToggle(true);
console.log(toggle);
//=> true

Alternatively, you can pass a function to the updater. This is called a functional update. The updater will call the function with the previous state value and update the state to whatever the function returns.

const handleToggle = (prevToggle) => {
  return !prevToggle;
}

console.log(toggle);
//=> true

setToggle(handleToggle);

console.log(toggle);
//=> false