Skip to content
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

update last challenge to be be a better use of ref #5485

Open
wants to merge 4 commits 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
17 changes: 5 additions & 12 deletions src/content/learn/referencing-values-with-refs.md
Original file line number Diff line number Diff line change
Expand Up @@ -616,33 +616,26 @@ 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 input in a ref. Instead of storing the value in state you are simply reading the native value of the input. This is called an [uncontrolled component]().

<Sandpack>

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

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

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

function handleSend() {
setTimeout(() => {
alert('Sending: ' + textRef.current);
alert('Sending: ' + textRef.current.value);
}, 3000);
}

return (
<>
<input
value={text}
onChange={handleChange}
ref={textRef}
/>
<button
onClick={handleSend}>
Expand Down
Loading