'You Might Not Need an Effect'·续3
function handleAddClick() { setText(''); setTodos([...todos, createTodo(text)]); }
return ( <> <label> <input type="checkbox" checked={showActive} onChange={e => setShowActive(e.target.checked)} /> Show only active todos </label> <input value={text} onChange={e => setText(e.target.value)} /> <button onClick={handleAddClick}> Add </button> <ul> {visibleTodos.map(todo => ( <li key={todo.id}> {todo.completed ? <s>{todo.text}</s> : todo.text} </li> ))} </ul> </> ); }
```js src/todos.js
let nextId = 0;
let calls = 0;
export function getVisibleTodos(todos, showActive) {
console.log(`getVisibleTodos() was called ${++calls} times`);
const activeTodos = todos.filter(todo => !todo.completed);
const visibleTodos = showActive ? activeTodos : todos;
return visibleTodos;
}
export function createTodo(text, completed = false) {
return {
id: nextId++,
text,
completed
};
}
export const initialTodos = [
createTodo('Get apples', true),
createTodo('Get oranges', true),
createTodo('Get carrots'),
];
label { display: block; }
input { margin-top: 10px; }
With this change, getVisibleTodos() will be called only if todos or showActive change. Typing into the input only changes the text state variable, so it does not trigger a call to getVisibleTodos().
There is also another solution which does not need useMemo. Since the text state variable can't possibly affect the list of todos, you can extract the NewTodo form into a separate component, and move the text state variable inside of it:
import { useState, useMemo } from 'react';
import { initialTodos, createTodo, getVisibleTodos } from './todos.js';
export default function TodoList() {
const [todos, setTodos] = useState(initialTodos);
const [showActive, setShowActive] = useState(false);
const visibleTodos = getVisibleTodos(todos, showActive);
return (
<>
<label>
<input
type="checkbox"
checked={showActive}
onChange={e => setShowActive(e.target.checked)}
/>
Show only active todos
</label>
<NewTodo onAdd={newTodo => setTodos([...todos, newTodo])} />
<ul>
{visibleTodos.map(todo => (
<li key={todo.id}>
{todo.completed ? <s>{todo.text}</s> : todo.text}
</li>
))}
</ul>
</>
);
}
function NewTodo({ onAdd }) {
const [text, setText] = useState('');
function handleAddClick() {
setText('');
onAdd(createTodo(text));
}
return (
<>
<input value={text} onChange={e => setText(e.target.value)} />
<button onClick={handleAddClick}>
Add
</button>
</>
);
}
```js src/todos.js let nextId = 0; let calls = 0;
export function getVisibleTodos(todos, showActive) {
console.log(getVisibleTodos() was called ${++calls} times);
const activeTodos = todos.filter(todo => !todo.completed);
const visibleTodos = showActive ? activeTodos : todos;
return visibleTodos;
}
export function createTodo(text, completed = false) { return { id: nextId++, text, completed }; }
export const initialTodos = [ createTodo('Get apples', true), createTodo('Get oranges', true), createTodo('Get carrots'), ];
```css
label { display: block; }
input { margin-top: 10px; }
This approach satisfies the requirements too. When you type into the input, only the text state variable updates. Since the text state variable is in the child NewTodo component, the parent TodoList component won't get re-rendered. This is why getVisibleTodos() doesn't get called when you type. (It would still be called if the TodoList re-renders for another reason.)
Reset state without Effects
This EditContact component receives a contact object shaped like { id, name, email } as the savedContact prop. Try editing the name and email input fields. When you press Save, the contact's button above the form updates to the edited name. When you press Reset, any pending changes in the form are discarded. Play around with this UI to get a feel for it.
When you select a contact with the buttons at the top, the form resets to reflect that contact's details. This is done with an Effect inside EditContact.js. Remove this Effect. Find another way to reset the form when savedContact.id changes.
```js src/App.js hidden import { useState } from 'react'; import ContactList from './ContactList.js'; import EditContact from './EditContact.js';
export default function ContactManager() { const [ contacts, setContacts ] = useState(initialContacts); const [ selectedId, setSelectedId ] = useState(0); const selectedContact = contacts.find(c => c.id === selectedId );
function handleSave(updatedData) { const nextContacts = contacts.map(c => { if (c.id === updatedData.id) { return updatedData; } else { return c; } }); setContacts(nextContacts); }
return ( <div> <ContactList contacts={contacts} selectedId={selectedId} onSelect={id => setSelectedId(id)} /> <hr /> <EditContact savedContact={selectedContact} onSave={handleSave} /> </div> ) }
const initialContacts = [ { id: 0, name: 'Taylor', email: 'taylor@mail.com' }, { id: 1, name: 'Alice', email: 'alice@mail.com' }, { id: 2, name: 'Bob', email: 'bob@mail.com' } ];
```js src/ContactList.js hidden
export default function ContactList({
contacts,
selectedId,
onSelect
}) {
return (
<section>
<ul>
{contacts.map(contact =>
<li key={contact.id}>
<button onClick={() => {
onSelect(contact.id);
}}>
{contact.id === selectedId ?
<b>{contact.name}</b> :
contact.name
}
</button>
</li>
)}
</ul>
</section>
);
}
```js {expectedErrors: {'react-compiler': [8, 9]}} src/EditContact.js active import { useState, useEffect } from 'react';
export default function EditContact({ savedContact, onSave }) { const [name, setName] = useState(savedContact.name); const [email, setEmail] = useState(savedContact.email);
useEffect(() => { setName(savedContact.name); setEmail(savedContact.email); }, [savedContact]);
return ( <section> <label> Name:{' '} <input type="text" value={name} onChange={e => setName(e.target.value)} /> </label> <label> Email:{' '} <input type="email" value={email} onChange={e => setEmail(e.target.value)} /> </label> <button onClick={() => { const updatedData = { id: savedContact.id, name: name, email: email }; onSave(updatedData); }}> Save </button> <button onClick={() => { setName(savedContact.name); setEmail(savedContact.email); }}> Reset </button> </section> ); }
```css
ul, li {
list-style: none;
margin: 0;
padding: 0;
}
li { display: inline-block; }
li button {
padding: 10px;
}
label {
display: block;
margin: 10px 0;
}
button {
margin-right: 10px;
margin-bottom: 10px;
}
It would be nice if there was a way to tell React that when savedContact.id is different, the EditContact form is conceptually a different contact's form and should not preserve state. Do you recall any such way?
Split the EditContact component in two. Move all the form state into the inner EditForm component. Export the outer EditContact component, and make it pass savedContact.id as the key to the inner EditForm component. As a result, the inner EditForm component resets all of the form state and recreates the DOM whenever you select a different contact.
```js src/App.js hidden import { useState } from 'react'; import ContactList from './ContactList.js'; import EditContact from './EditContact.js';
export default function ContactManager() { const [ contacts, setContacts ] = useState(initialContacts); const [ selectedId, setSelectedId ] = useState(0); const selectedContact = contacts.find(c => c.id === selectedId );
function handleSave(updatedData) { const nextContacts = contacts.map(c => { if (c.id === updatedData.id) { return updatedData; } else { return c; } }); setContacts(nextContacts); }
return ( <div> <ContactList contacts={contacts} selectedId={selectedId} onSelect={id => setSelectedId(id)} /> <hr /> <EditContact savedContact={selectedContact} onSave={handleSave} /> </div> ) }
const initialContacts = [ { id: 0, name: 'Taylor', email: 'taylor@mail.com' }, { id: 1, name: 'Alice', email: 'alice@mail.com' }, { id: 2, name: 'Bob', email: 'bob@mail.com' } ];
```js src/ContactList.js hidden
export default function ContactList({
contacts,
selectedId,
onSelect
}) {
return (
<section>
<ul>
{contacts.map(contact =>
<li key={contact.id}>
<button onClick={() => {
onSelect(contact.id);
}}>
{contact.id === selectedId ?
<b>{contact.name}</b> :
contact.name
}
</button>
</li>
)}
</ul>
</section>
);
}
```js src/EditContact.js active import { useState } from 'react';
export default function EditContact(props) { return ( <EditForm {...props} key={props.savedContact.id} /> ); }
function EditForm({ savedContact, onSave }) { const [name, setName] = useState(savedContact.name); const [email, setEmail] = useState(savedContact.email);
return ( <section> <label> Name:{' '} <input type="text" value={name} onChange={e => setName(e.target.value)} /> </label> <label> Email:{' '} <input type="email" value={email} onChange={e => setEmail(e.target.value)} /> </label> <button onClick={() => { const updatedData = { id: savedContact.id, name: name, email: email }; onSave(updatedData); }}> Save </button> <button onClick={() => { setName(savedContact.name); setEmail(savedContact.email); }}> Reset </button> </section> ); }
```css
ul, li {
list-style: none;
margin: 0;
padding: 0;
}
li { display: inline-block; }
li button {
padding: 10px;
}
label {
display: block;
margin: 10px 0;
}
button {
margin-right: 10px;
margin-bottom: 10px;
}
Submit a form without Effects
This Form component lets you send a message to a friend. When you submit the form, the showForm state variable is set to false. This triggers an Effect calling sendMessage(message), which sends the message (you can see it in the console). After the message is sent, you see a "Thank you" dialog with an "Open chat" button that lets you get back to the form.
Your app's users are sending way too many messages. To make chatting a little bit more difficult, you've decided to show the "Thank you" dialog first rather than the form. Change the showForm state variable to initialize to false instead of true. As soon as you make that change, the console will show that an empty message was sent. Something in this logic is wrong!
What's the root cause of this problem? And how can you fix it?
Should the message be sent because the user saw the "Thank you" dialog? Or is it the other way around?
import { useState, useEffect } from 'react';
export default function Form() {
const [showForm, setShowForm] = useState(true);
const [message, setMessage] = useState('');
useEffect(() => {
if (!showForm) {
sendMessage(message);
}
}, [showForm, message]);
function handleSubmit(e) {
e.preventDefault();
setShowForm(false);
}
if (!showForm) {
return (
<>
<h1>Thanks for using our services!</h1>
<button onClick={() => {
setMessage('');
setShowForm(true);
}}>
Open chat
</button>
</>
);
}
return (
<form onSubmit={handleSubmit}>
<textarea
placeholder="Message"
value={message}
onChange={e => setMessage(e.target.value)}
/>
<button type="submit" disabled={message === ''}>
Send
</button>
</form>
);
}
function sendMessage(message) {
console.log('Sending message: ' + message);
}
label, textarea { margin-bottom: 10px; display: block; }
The showForm state variable determines whether to show the form or the "Thank you" dialog. However, you aren't sending the message because the "Thank you" dialog was displayed. You want to send the message because the user has submitted the form. Delete the misleading Effect and move the sendMessage call inside the handleSubmit event handler:
import { useState, useEffect } from 'react';
export default function Form() {
const [showForm, setShowForm] = useState(true);
const [message, setMessage] = useState('');
function handleSubmit(e) {
e.preventDefault();
setShowForm(false);
sendMessage(message);
}
if (!showForm) {
return (
<>
<h1>Thanks for using our services!</h1>
<button onClick={() => {
setMessage('');
setShowForm(true);
}}>
Open chat
</button>
</>
);
}
return (
<form onSubmit={handleSubmit}>
<textarea
placeholder="Message"
value={message}
onChange={e => setMessage(e.target.value)}
/>
<button type="submit" disabled={message === ''}>
Send
</button>
</form>
);
}
function sendMessage(message) {
console.log('Sending message: ' + message);
}
label, textarea { margin-bottom: 10px; display: block; }
Notice how in this version, only submitting the form (which is an event) causes the message to be sent. It works equally well regardless of whether showForm is initially set to true or false. (Set it to false and notice no extra console messages.)
