Repeat useEffect of names in array
P粉775788723
P粉775788723 2023-08-14 18:14:44
0
1
403
<p>I found this exercise on this website; I'm testing this as I'm also learning hooks in React. </p> <p>I don't understand why the execution of useEffect stops when you enter a name that is the same as one already in the array. </p> <p>Shouldn't it skip duplicate names and move on to the next one? Or am I doing something wrong? </p> <pre class="brush:php;toolbar:false;">let users = ['Oliver', 'Thomas', 'George', 'George', 'William'] export default function App() { const [index, setIndex] = useState(0); console.log('RENDER'); useEffect(() => { setTimeout(() => setIndex(index => index 1), 1000) console.log('Hello ' users[index]); console.log('Side Effect RUNS!'); if (index === users.length - 1) { return } }, [users[index]]) }</pre> <p><br /></p>
P粉775788723
P粉775788723

reply all(1)
P粉034571623

Side effects in loops: The way you use setTimeout and setIndex in useEffect may cause unexpected behavior. useEffect is executed after each render, and using the index state directly in the setTimeout callback may cause problems because the closure captures the state value when the callback is created.

Accessing array elements: You are trying to access an element of the users array using an index, but due to the asynchronous nature of useEffect and delay, it is possible to exceed the scope of the array.

const [index, setIndex] = useState(0);

  useEffect(() => {
    console.log('RENDER');
    console.log('副作用运行!');
    
    if (index >= users.length) {
      return;
    }

    const timeoutId = setTimeout(() => {
      console.log('你好 ' + users[index]);
      setIndex(index + 1);
    }, 1000);

    return () => clearTimeout (timeoutId);
  }, [index]);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template