-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Docs for cacheSignal
#8023
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
eps1lon
wants to merge
4
commits into
reactjs:main
Choose a base branch
from
eps1lon:sebbie/09-26-docs_for_cachesignal_
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+134
−10
Open
Docs for cacheSignal
#8023
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
--- | ||
title: cacheSignal | ||
--- | ||
|
||
<Canary> | ||
|
||
**The `cacheSignal()` API is currently only available in React’s Canary and Experimental channels.** | ||
|
||
[Learn more about React’s release channels here.](/community/versioning-policy#all-release-channels) | ||
|
||
</Canary> | ||
|
||
<RSC> | ||
|
||
`cacheSignal` is currently only used with [React Server Components](/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023#react-server-components). | ||
|
||
</RSC> | ||
|
||
<Intro> | ||
|
||
`cacheSignal` allows you to know when the `cache()` life time is over. | ||
|
||
```js | ||
const signal = cacheSignal(); | ||
``` | ||
|
||
</Intro> | ||
|
||
<InlineToc /> | ||
|
||
--- | ||
|
||
## Reference {/*reference*/} | ||
|
||
### `cacheSignal` {/*cachesignal*/} | ||
|
||
Call `cacheSignal` to get an `AbortSignal`. | ||
|
||
```js {3,7} | ||
import {cacheSignal} from 'react'; | ||
async function Component() { | ||
await fetch(url, { signal: cacheSignal() }); | ||
} | ||
``` | ||
|
||
When React has finished rendering, the `AbortSignal` will be aborted. This allows you to cancel any in-flight work that is no longer needed. | ||
Rendering is considered finished when: | ||
- React has successfully completed rendering | ||
- the render was aborted | ||
- the render has failed | ||
|
||
#### Parameters {/*parameters*/} | ||
|
||
This function does not accept any parameters. | ||
|
||
#### Returns {/*returns*/} | ||
|
||
`cacheSignal` returns an `AbortSignal` if called during rendering. Otherwise `cacheSignal()` returns `null`. | ||
|
||
#### Caveats {/*caveats*/} | ||
|
||
- `cacheSignal` is currently for use in [React Server Components](/reference/rsc/server-components) only. In Client Components, it will always return `null`. In the future it will also be used for Client Component when a client cache refreshes or invalidates. You should not assume it'll always be null on the client. | ||
- If called outside of rendering, `cacheSignal` will return `null` to make it clear that the current scope isn't cached forever. | ||
|
||
--- | ||
|
||
## Usage {/*usage*/} | ||
|
||
### Cancel in-flight requests {/*cancel-in-flight-requests*/} | ||
|
||
Call <CodeStep step={1}>`cacheSignal`</CodeStep> to abort in-flight requests. | ||
|
||
```js [[1, 4, "cacheSignal()"]] | ||
import {cache, cacheSignal} from 'react'; | ||
const dedupedFetch = cache(fetch); | ||
async function Component() { | ||
await dedupedFetch(url, { signal: cacheSignal() }); | ||
} | ||
``` | ||
|
||
<Pitfall> | ||
You can't use `cacheSignal` to abort async work that was started outside of rendering e.g. | ||
|
||
```js | ||
import {cacheSignal} from 'react'; | ||
// 🚩 Pitfall: The request will not actually be aborted if the rendering of `Component` is finished. | ||
const response = fetch(url, { signal: cacheSignal() }); | ||
async function Component() { | ||
await response; | ||
} | ||
``` | ||
</Pitfall> | ||
|
||
### Ignore errors after React has finished rendering {/*ignore-errors-after-react-has-finished-rendering*/} | ||
|
||
If a function throws, it may be due to cancellation (e.g. <CodeStep step={1}>the Database connection</CodeStep> has been closed). You can use the <CodeStep step={2}>`aborted` property</CodeStep> to check if the error was due to cancellation or a real error. You may want to <CodeStep step={3}>ignore errors</CodeStep> that were due to cancellation. | ||
|
||
```js [[1, 2, "./database"], [2, 8, "cacheSignal()?.aborted"], [3, 12, "return null"]] | ||
import {cacheSignal} from "react"; | ||
import {queryDatabase, logError} from "./database"; | ||
|
||
async function getData(id) { | ||
try { | ||
return await queryDatabase(id); | ||
} catch (x) { | ||
if (!cacheSignal()?.aborted) { | ||
// only log if it's a real error and not due to cancellation | ||
logError(x); | ||
} | ||
return null; | ||
} | ||
} | ||
|
||
async function Component({id}) { | ||
const data = await getData(id); | ||
if (data === null) { | ||
return <div>No data available</div>; | ||
} | ||
return <div>{data.name}</div>; | ||
} | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This example doesn't make sense because you have no idea that the fetch here is using
cache()
.Can you use something like a DB example, like here?
https://react-do5kq6ru7-fbopensource.vercel.app/reference/react/cache#preload-data
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You don't need to know if the call is cached or not. Just that it may be cached by
cache()
.