diff --git a/README.md b/README.md index 735488d..57cf521 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_968 TILs and counting..._ +_969 TILs and counting..._ --- @@ -684,6 +684,7 @@ _968 TILs and counting..._ - [Mock A Function That A Component Imports](react/mock-a-function-that-a-component-imports.md) - [Navigate With State Via @reach/router](react/navigate-with-state-via-reach-router.md) - [Pairing A Callback With A useState Hook](react/pairing-a-callback-with-a-usestate-hook.md) +- [Pass A Function To A useState Updater](react/pass-a-function-to-a-usestate-updater.md) - [Passing Props Down To React-Router Route](react/passing-props-down-to-react-router-route.md) - [Prevent reach/router Redirect Error Screen In Dev](react/prevent-reach-router-redirect-error-screen-in-dev.md) - [Proxy To An API Server In Development With CRA](react/proxy-to-an-api-server-in-development-with-cra.md) diff --git a/react/pass-a-function-to-a-usestate-updater.md b/react/pass-a-function-to-a-usestate-updater.md new file mode 100644 index 0000000..ffdc2b9 --- /dev/null +++ b/react/pass-a-function-to-a-usestate-updater.md @@ -0,0 +1,36 @@ +# Pass A Function To A useState Updater + +Let's say you have a component with a toggle state: + +```javascript +const [toggle, setToggle] = useState(false); +``` + +You can change the state of the toggle by directly passing a value to +`setToggle`. + +```javascript +setToggle(true); +console.log(toggle); +//=> true +``` + +Alternatively, you can pass a function to the updater. This is called a +[_functional +update_](https://reactjs.org/docs/hooks-reference.html#functional-updates). The +updater will call the function with the previous state value and update the +state to whatever the function returns. + +```javascript +const handleToggle = (prevToggle) => { + return !prevToggle; +} + +console.log(toggle); +//=> true + +setToggle(handleToggle); + +console.log(toggle); +//=> false +```