'Removing Effect Dependencies'·续3

This code already works, but there is something you want to change. Currently, when you move the slider that controls the duration state variable, it retriggers the animation. Change the behavior so that the Effect does not "react" to the duration variable. When you press "Show", the Effect should use the current duration on the slider. However, moving the slider itself should not by itself retrigger the animation.

Is there a line of code inside the Effect that should not be reactive? How can you move non-reactive code out of the Effect?

import { useState, useEffect, useRef } from 'react';
import { useEffectEvent } from 'react';
import { FadeInAnimation } from './animation.js';

function Welcome({ duration }) {
  const ref = useRef(null);

useEffect(() => {
    const animation = new FadeInAnimation(ref.current);
    animation.start(duration);
    return () => {
      animation.stop();
    };
  }, [duration]);

return (
    <h1
      ref={ref}
      style={{
        opacity: 0,
        color: 'white',
        padding: 50,
        textAlign: 'center',
        fontSize: 50,
        backgroundImage: 'radial-gradient(circle, rgba(63,94,251,1) 0%, rgba(252,70,107,1) 100%)'
      }}
    >
      Welcome
    </h1>
  );
}

export default function App() {
  const [duration, setDuration] = useState(1000);
  const [show, setShow] = useState(false);

return (
    <>
      <label>
        <input
          type="range"
          min="100"
          max="3000"
          value={duration}
          onChange={e => setDuration(Number(e.target.value))}
        />
        <br />
        Fade in duration: {duration} ms
      </label>
      <button onClick={() => setShow(!show)}>
        {show ? 'Remove' : 'Show'}
      </button>
      <hr />
      {show && <Welcome duration={duration} />}
    </>
  );
}

```js src/animation.js export class FadeInAnimation { constructor(node) { this.node = node; } start(duration) { this.duration = duration; if (this.duration === 0) { // Jump to end immediately this.onProgress(1); } else { this.onProgress(0); // Start animating this.startTime = performance.now(); this.frameId = requestAnimationFrame(() => this.onFrame()); } } onFrame() { const timePassed = performance.now() - this.startTime; const progress = Math.min(timePassed / this.duration, 1); this.onProgress(progress); if (progress < 1) { // We still have more frames to paint this.frameId = requestAnimationFrame(() => this.onFrame()); } } onProgress(progress) { this.node.style.opacity = progress; } stop() { cancelAnimationFrame(this.frameId); this.startTime = null; this.frameId = null; this.duration = 0; } }


```css
label, button { display: block; margin-bottom: 20px; }
html, body { min-height: 300px; }

Your Effect needs to read the latest value of duration, but you don't want it to "react" to changes in duration. You use duration to start the animation, but starting animation isn't reactive. Extract the non-reactive line of code into an Effect Event, and call that function from your Effect.

import { useState, useEffect, useRef } from 'react';
import { FadeInAnimation } from './animation.js';
import { useEffectEvent } from 'react';

function Welcome({ duration }) {
  const ref = useRef(null);

const onAppear = useEffectEvent(animation => {
    animation.start(duration);
  });

useEffect(() => {
    const animation = new FadeInAnimation(ref.current);
    onAppear(animation);
    return () => {
      animation.stop();
    };
  }, []);

return (
    <h1
      ref={ref}
      style={{
        opacity: 0,
        color: 'white',
        padding: 50,
        textAlign: 'center',
        fontSize: 50,
        backgroundImage: 'radial-gradient(circle, rgba(63,94,251,1) 0%, rgba(252,70,107,1) 100%)'
      }}
    >
      Welcome
    </h1>
  );
}

export default function App() {
  const [duration, setDuration] = useState(1000);
  const [show, setShow] = useState(false);

return (
    <>
      <label>
        <input
          type="range"
          min="100"
          max="3000"
          value={duration}
          onChange={e => setDuration(Number(e.target.value))}
        />
        <br />
        Fade in duration: {duration} ms
      </label>
      <button onClick={() => setShow(!show)}>
        {show ? 'Remove' : 'Show'}
      </button>
      <hr />
      {show && <Welcome duration={duration} />}
    </>
  );
}

```js src/animation.js export class FadeInAnimation { constructor(node) { this.node = node; } start(duration) { this.duration = duration; this.onProgress(0); this.startTime = performance.now(); this.frameId = requestAnimationFrame(() => this.onFrame()); } onFrame() { const timePassed = performance.now() - this.startTime; const progress = Math.min(timePassed / this.duration, 1); this.onProgress(progress); if (progress < 1) { // We still have more frames to paint this.frameId = requestAnimationFrame(() => this.onFrame()); } } onProgress(progress) { this.node.style.opacity = progress; } stop() { cancelAnimationFrame(this.frameId); this.startTime = null; this.frameId = null; this.duration = 0; } }


```css
label, button { display: block; margin-bottom: 20px; }
html, body { min-height: 300px; }

Effect Events like onAppear are not reactive, so you can read duration inside without retriggering the animation.

Fix a reconnecting chat

In this example, every time you press "Toggle theme", the chat re-connects. Why does this happen? Fix the mistake so that the chat re-connects only when you edit the Server URL or choose a different chat room.

Treat chat.js as an external third-party library: you can consult it to check its API, but don't edit it.

There's more than one way to fix this, but ultimately you want to avoid having an object as your dependency.

```js src/App.js import { useState } from 'react'; import ChatRoom from './ChatRoom.js';

export default function App() { const [isDark, setIsDark] = useState(false); const [roomId, setRoomId] = useState('general'); const [serverUrl, setServerUrl] = useState('https://localhost:1234');

const options = { serverUrl: serverUrl, roomId: roomId };

return (


); }


```js src/ChatRoom.js active
import { useEffect } from 'react';
import { createConnection } from './chat.js';

export default function ChatRoom({ options }) {
  useEffect(() => {
    const connection = createConnection(options);
    connection.connect();
    return () => connection.disconnect();
  }, [options]);

return <h1>Welcome to the {options.roomId} room!</h1>;
}

```js src/chat.js export function createConnection({ serverUrl, roomId }) { // A real implementation would actually connect to the server if (typeof serverUrl !== 'string') { throw Error('Expected serverUrl to be a string. Received: ' + serverUrl); } if (typeof roomId !== 'string') { throw Error('Expected roomId to be a string. Received: ' + roomId); } return { connect() { console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); }, disconnect() { console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); } }; }


```css
label, button { display: block; margin-bottom: 5px; }
.dark { background: #222; color: #eee; }

Your Effect is re-running because it depends on the options object. Objects can be re-created unintentionally, you should try to avoid them as dependencies of your Effects whenever possible.

The least invasive fix is to read roomId and serverUrl right outside the Effect, and then make the Effect depend on those primitive values (which can't change unintentionally). Inside the Effect, create an object and pass it to createConnection:

```js src/App.js import { useState } from 'react'; import ChatRoom from './ChatRoom.js';

export default function App() { const [isDark, setIsDark] = useState(false); const [roomId, setRoomId] = useState('general'); const [serverUrl, setServerUrl] = useState('https://localhost:1234');

const options = { serverUrl: serverUrl, roomId: roomId };

return (


); }


```js src/ChatRoom.js active
import { useEffect } from 'react';
import { createConnection } from './chat.js';

export default function ChatRoom({ options }) {
  const { roomId, serverUrl } = options;
  useEffect(() => {
    const connection = createConnection({
      roomId: roomId,
      serverUrl: serverUrl
    });
    connection.connect();
    return () => connection.disconnect();
  }, [roomId, serverUrl]);

return <h1>Welcome to the {options.roomId} room!</h1>;
}

```js src/chat.js export function createConnection({ serverUrl, roomId }) { // A real implementation would actually connect to the server if (typeof serverUrl !== 'string') { throw Error('Expected serverUrl to be a string. Received: ' + serverUrl); } if (typeof roomId !== 'string') { throw Error('Expected roomId to be a string. Received: ' + roomId); } return { connect() { console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); }, disconnect() { console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); } }; }


```css
label, button { display: block; margin-bottom: 5px; }
.dark { background: #222; color: #eee; }

It would be even better to replace the object options prop with the more specific roomId and serverUrl props:

```js src/App.js import { useState } from 'react'; import ChatRoom from './ChatRoom.js';

export default function App() { const [isDark, setIsDark] = useState(false); const [roomId, setRoomId] = useState('general'); const [serverUrl, setServerUrl] = useState('https://localhost:1234');

return (


); }


```js src/ChatRoom.js active
import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';

export default function ChatRoom({ roomId, serverUrl }) {
  useEffect(() => {
    const connection = createConnection({
      roomId: roomId,
      serverUrl: serverUrl
    });
    connection.connect();
    return () => connection.disconnect();
  }, [roomId, serverUrl]);

return <h1>Welcome to the {roomId} room!</h1>;
}

```js src/chat.js export function createConnection({ serverUrl, roomId }) { // A real implementation would actually connect to the server if (typeof serverUrl !== 'string') { throw Error('Expected serverUrl to be a string. Received: ' + serverUrl); } if (typeof roomId !== 'string') { throw Error('Expected roomId to be a string. Received: ' + roomId); } return { connect() { console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); }, disconnect() { console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); } }; }


```css
label, button { display: block; margin-bottom: 5px; }
.dark { background: #222; color: #eee; }

Sticking to primitive props where possible makes it easier to optimize your components later.

Fix a reconnecting chat, again

This example connects to the chat either with or without encryption. Toggle the checkbox and notice the different messages in the console when the encryption is on and off. Try changing the room. Then, try toggling the theme. When you're connected to a chat room, you will receive new messages every few seconds. Verify that their color matches the theme you've picked.

In this example, the chat re-connects every time you try to change the theme. Fix this. After the fix, changing the theme should not re-connect the chat, but toggling encryption settings or changing the room should re-connect.

Don't change any code in chat.js. Other than that, you can change any code as long as it results in the same behavior. For example, you may find it helpful to change which props are being passed down.

You're passing down two functions: onMessage and createConnection. Both of them are created from scratch every time App re-renders. They are considered to be new values every time, which is why they re-trigger your Effect.

One of these functions is an event handler. Do you know some way to call an event handler an Effect without "reacting" to the new values of the event handler function? That would come in handy!

Another of these functions only exists to pass some state to an imported API method. Is this function really necessary? What is the essential information that's being passed down? You might need to move some imports from App.js to ChatRoom.js.