1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-04 23:58:01 +00:00

Add Pairing A Callback With A useState Hook as a react til

This commit is contained in:
jbranchaud
2019-08-27 11:45:35 -05:00
parent b207b9edff
commit 66a1546bc7
2 changed files with 46 additions and 1 deletions

View File

@@ -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)

View File

@@ -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 (
<div>
{loading && <p>Loading...</p>}
<button onClick={toggleLoading}>{loading ? "Cancel" : "Save"}</button>
</div>
);
}
```
The `useState` acts on its own. It has no side-effects. We follow it with a
`useEffect` that responds to changes to the value of `loading` -- this is where
our _callback_ gets invoked.
See a [live example](https://codesandbox.io/s/clever-roentgen-kvzze).