Skip to content

[Beta] Suggest/referencing values with refs #5097

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
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions beta/src/content/learn/referencing-values-with-refs.md
Original file line number Diff line number Diff line change
@@ -616,19 +616,17 @@ export default function Chat() {

<Solution>

State works [like a snapshot](/learn/state-as-a-snapshot), so you can't read the latest state from an asynchronous operation like a timeout. However, you can keep the latest input text in a ref. A ref is mutable, so you can read the `current` property at any time. Since the current text is also used for rendering, in this example, you will need *both* a state variable (for rendering), *and* a ref (to read it in the timeout). You will need to update the current ref value manually.
State works [like a snapshot](/learn/state-as-a-snapshot), so you can't read the latest state from an asynchronous operation like a timeout. However, you can keep the latest input text in a ref. A ref is mutable, so you can read the `current` property at any time.

<Sandpack>

```js
import { useState, useRef } from 'react';
import { useRef } from 'react';

export default function Chat() {
const [text, setText] = useState('');
const textRef = useRef(text);
const textRef = useRef('');

function handleChange(e) {
setText(e.target.value);
textRef.current = e.target.value;
}

@@ -641,7 +639,7 @@ export default function Chat() {
return (
<>
<input
value={text}
defaultValue={textRef.current}
Copy link
Collaborator

@eps1lon eps1lon Oct 8, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem here is that this example reads from a ref during render. Even if that specific prop is only relevant once, the overall pattern is still problematic. React might even warn if defaultValue changes. But the biggest problem is reading from a ref during render which we probably shouldn't showcase.

onChange={handleChange}
/>
<button