diff --git a/README.md b/README.md index eff6aca..d8b51a6 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_838 TILs and counting..._ +_839 TILs and counting..._ --- @@ -562,6 +562,7 @@ _838 TILs and counting..._ - [Mapping Over One Or Many Children](react/mapping-over-one-or-many-children.md) - [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) - [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/pairing-a-callback-with-a-usestate-hook.md b/react/pairing-a-callback-with-a-usestate-hook.md new file mode 100644 index 0000000..c366d72 --- /dev/null +++ b/react/pairing-a-callback-with-a-usestate-hook.md @@ -0,0 +1,44 @@ +# Pairing A Callback With A useState Hook + +React's Class-based state management allowed you to update the state of your +component with a call to `this.setState()`. The first argument represents the +changes to the state. It also accepts a second argument; a callback that will +be invoked after the state has been updated. + +```javascript +this.setState({ loading: true }, () => console.log("Loading...")); +``` + +If you've transitioned to Hooks-based state management, then you may have +noticed that the updaters generated by `useState` calls do not accept a second +callback argument. + +If you want to update state and fire a callback in response to it, you can pair +`useState` with `useEffect`. + +```javascript +import React, { useState, useEffect } from "react"; + +function App() { + const [loading, setLoading] = useState(false); + const toggleLoading = () => setLoading(prevLoading => !prevLoading); + useEffect(() => { + if(loading) { + console.log("We are loading now"); + } + }, [loading]) + + return ( +
Loading...
} + +