Keeping Components Pure·续

function useTime() { const [time, setTime] = useState(() => new Date()); useEffect(() => { const id = setInterval(() => { setTime(new Date()); }, 1000); return () => clearInterval(id); }, []); return time; }

export default function App() { const time = useTime(); return ( <Clock time={time} /> ); }


```css
body > * {
  width: 100%;
  height: 100%;
}
.day {
  background: #fff;
  color: #222;
}
.night {
  background: #222;
  color: #fff;
}

You can fix this component by calculating the className and including it in the render output:

```js src/Clock.js active export default function Clock({ time }) { const hours = time.getHours(); let className; if (hours >= 0 && hours <= 6) { className = 'night'; } else { className = 'day'; } return ( <h1 className={className}> {time.toLocaleTimeString()} </h1> ); }


```js src/App.js hidden
import { useState, useEffect } from 'react';
import Clock from './Clock.js';

function useTime() {
  const [time, setTime] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => {
      setTime(new Date());
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return time;
}

export default function App() {
  const time = useTime();
  return (
    &lt;Clock time={time} />
  );
}
body > * {
  width: 100%;
  height: 100%;
}
.day {
  background: #fff;
  color: #222;
}
.night {
  background: #222;
  color: #fff;
}

In this example, the side effect (modifying the DOM) was not necessary at all. You only needed to return JSX.

Fix a broken profile

Two Profile components are rendered side by side with different data. Press "Collapse" on the first profile, and then "Expand" it. You'll notice that both profiles now show the same person. This is a bug.

Find the cause of the bug and fix it.

The buggy code is in Profile.js. Make sure you read it all from top to bottom!

```js {expectedErrors: {'react-compiler': [7]}} src/Profile.js import Panel from './Panel.js'; import { getImageUrl } from './utils.js';

let currentPerson;

export default function Profile({ person }) { currentPerson = person; return ( <Panel> <Header /> <Avatar /> </Panel> ) }

function Header() { return <h1>{currentPerson.name}</h1>; }

function Avatar() { return ( <img className="avatar" src={getImageUrl(currentPerson)} alt={currentPerson.name} width={50} height={50} /> ); }


```js src/Panel.js hidden
import { useState } from 'react';

export default function Panel({ children }) {
  const [open, setOpen] = useState(true);
  return (
    &lt;section className="panel">
      &lt;button onClick={() => setOpen(!open)}>
        {open ? 'Collapse' : 'Expand'}
      &lt;/button>
      {open && children}
    &lt;/section>
  );
}

```js src/App.js import Profile from './Profile.js';

export default function App() { return ( <> <Profile person={{ imageId: 'lrWQx8l', name: 'Subrahmanyan Chandrasekhar', }} /> <Profile person={{ imageId: 'MK3eW3A', name: 'Creola Katherine Johnson', }} /> </> ) }


```js src/utils.js hidden
export function getImageUrl(person, size = 's') {
  return (
    'https://react.dev/images/docs/scientists/' +
    person.imageId +
    size +
    '.jpg'
  );
}
.avatar { margin: 5px; border-radius: 50%; }
.panel {
  border: 1px solid #aaa;
  border-radius: 6px;
  margin-top: 20px;
  padding: 10px;
  width: 200px;
}
h1 { margin: 5px; font-size: 18px; }

The problem is that the Profile component writes to a preexisting variable called currentPerson, and the Header and Avatar components read from it. This makes all three of them impure and difficult to predict.

To fix the bug, remove the currentPerson variable. Instead, pass all information from Profile to Header and Avatar via props. You'll need to add a person prop to both components and pass it all the way down.

```js src/Profile.js active import Panel from './Panel.js'; import { getImageUrl } from './utils.js';

export default function Profile({ person }) { return ( <Panel> <Header person={person} /> <Avatar person={person} /> </Panel> ) }

function Header({ person }) { return <h1>{person.name}</h1>; }

function Avatar({ person }) { return ( <img className="avatar" src={getImageUrl(person)} alt={person.name} width={50} height={50} /> ); }


```js src/Panel.js hidden
import { useState } from 'react';

export default function Panel({ children }) {
  const [open, setOpen] = useState(true);
  return (
    &lt;section className="panel">
      &lt;button onClick={() => setOpen(!open)}>
        {open ? 'Collapse' : 'Expand'}
      &lt;/button>
      {open && children}
    &lt;/section>
  );
}

```js src/App.js import Profile from './Profile.js';

export default function App() { return ( <> <Profile person={{ imageId: 'lrWQx8l', name: 'Subrahmanyan Chandrasekhar', }} /> <Profile person={{ imageId: 'MK3eW3A', name: 'Creola Katherine Johnson', }} /> </> ); }


```js src/utils.js hidden
export function getImageUrl(person, size = 's') {
  return (
    'https://react.dev/images/docs/scientists/' +
    person.imageId +
    size +
    '.jpg'
  );
}
.avatar { margin: 5px; border-radius: 50%; }
.panel {
  border: 1px solid #aaa;
  border-radius: 6px;
  margin-top: 20px;
  padding: 10px;
  width: 200px;
}
h1 { margin: 5px; font-size: 18px; }

Remember that React does not guarantee that component functions will execute in any particular order, so you can't communicate between them by setting variables. All communication must happen through props.

Fix a broken story tray

The CEO of your company is asking you to add "stories" to your online clock app, and you can't say no. You've written a StoryTray component that accepts a list of stories, followed by a "Create Story" placeholder.

You implemented the "Create Story" placeholder by pushing one more fake story at the end of the stories array that you receive as a prop. But for some reason, "Create Story" appears more than once. Fix the issue.

```js src/StoryTray.js active export default function StoryTray({ stories }) { stories.push({ id: 'create', label: 'Create Story' });

return ( <ul> {stories.map(story => ( <li key={story.id}> {story.label} </li> ))} </ul> ); }


```js {expectedErrors: {'react-compiler': [16]}} src/App.js hidden
import { useState, useEffect } from 'react';
import StoryTray from './StoryTray.js';

const initialStories = [
  {id: 0, label: "Ankit's Story" },
  {id: 1, label: "Taylor's Story" },
];

export default function App() {
  const [stories, setStories] = useState([...initialStories])
  const time = useTime();

// HACK: Prevent the memory from growing forever while you read docs.
  // We're breaking our own rules here.
  if (stories.length > 100) {
    stories.length = 100;
  }

return (
    &lt;div
      style={{
        width: '100%',
        height: '100%',
        textAlign: 'center',
      }}
    >
      &lt;h2>It is {time.toLocaleTimeString()} now.&lt;/h2>
      &lt;StoryTray stories={stories} />
    &lt;/div>
  );
}

function useTime() {
  const [time, setTime] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => {
      setTime(new Date());
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return time;
}
ul {
  margin: 0;
  list-style-type: none;
}

li {
  border: 1px solid #aaa;
  border-radius: 6px;
  float: left;
  margin: 5px;
  margin-bottom: 20px;
  padding: 5px;
  width: 70px;
  height: 100px;
}

```js sandbox.config.json hidden { "hardReloadOnChange": true }


Notice how whenever the clock updates, "Create Story" is added *twice*. This serves as a hint that we have a mutation during rendering--Strict Mode calls components twice to make these issues more noticeable.

`StoryTray` function is not pure. By calling `push` on the received `stories` array (a prop!), it is mutating an object that was created *before* `StoryTray` started rendering. This makes it buggy and very difficult to predict.

The simplest fix is to not touch the array at all, and render "Create Story" separately:

```js src/StoryTray.js active
export default function StoryTray({ stories }) {
  return (
    &lt;ul>
      {stories.map(story => (
        &lt;li key={story.id}>
          {story.label}
        &lt;/li>
      ))}
      &lt;li>Create Story&lt;/li>
    &lt;/ul>
  );
}

```js {expectedErrors: {'react-compiler': [16]}} src/App.js hidden import { useState, useEffect } from 'react'; import StoryTray from './StoryTray.js';

const initialStories = [ {id: 0, label: "Ankit's Story" }, {id: 1, label: "Taylor's Story" }, ];

export default function App() { const [stories, setStories] = useState([...initialStories]) const time = useTime();

// HACK: Prevent the memory from growing forever while you read docs. // We're breaking our own rules here. if (stories.length > 100) { stories.length = 100; }

return ( <div style={{ width: '100%', height: '100%', textAlign: 'center', }} > <h2>It is {time.toLocaleTimeString()} now.</h2> <StoryTray stories={stories} /> </div> ); }

function useTime() { const [time, setTime] = useState(() => new Date()); useEffect(() => { const id = setInterval(() => { setTime(new Date()); }, 1000); return () => clearInterval(id); }, []); return time; }


```css
ul {
  margin: 0;
  list-style-type: none;
}

li {
  border: 1px solid #aaa;
  border-radius: 6px;
  float: left;
  margin: 5px;
  margin-bottom: 20px;
  padding: 5px;
  width: 70px;
  height: 100px;
}

Alternatively, you could create a new array (by copying the existing one) before you push an item into it:

```js src/StoryTray.js active export default function StoryTray({ stories }) { // Copy the array! const storiesToDisplay = stories.slice();

// Does not affect the original array: storiesToDisplay.push({ id: 'create', label: 'Create Story' });

return ( <ul> {storiesToDisplay.map(story => ( <li key={story.id}> {story.label} </li> ))} </ul> ); }


```js {expectedErrors: {'react-compiler': [16]}} src/App.js hidden
import { useState, useEffect } from 'react';
import StoryTray from './StoryTray.js';

const initialStories = [
  {id: 0, label: "Ankit's Story" },
  {id: 1, label: "Taylor's Story" },
];

export default function App() {
  const [stories, setStories] = useState([...initialStories])
  const time = useTime();

// HACK: Prevent the memory from growing forever while you read docs.
  // We're breaking our own rules here.
  if (stories.length > 100) {
    stories.length = 100;
  }

return (
    &lt;div
      style={{
        width: '100%',
        height: '100%',
        textAlign: 'center',
      }}
    >
      &lt;h2>It is {time.toLocaleTimeString()} now.&lt;/h2>
      &lt;StoryTray stories={stories} />
    &lt;/div>
  );
}

function useTime() {
  const [time, setTime] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => {
      setTime(new Date());
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return time;
}
ul {
  margin: 0;
  list-style-type: none;
}

li {
  border: 1px solid #aaa;
  border-radius: 6px;
  float: left;
  margin: 5px;
  margin-bottom: 20px;
  padding: 5px;
  width: 70px;
  height: 100px;
}

This keeps your mutation local and your rendering function pure. However, you still need to be careful: for example, if you tried to change any of the array's existing items, you'd have to clone those items too.

It is useful to remember which operations on arrays mutate them, and which don't. For example, push, pop, reverse, and sort will mutate the original array, but slice, filter, and map will create a new one.


Sitemap

Overview of all docs pages