arlyxiao / best-practice

1 stars 0 forks source link

React infinite loop #80

Open arlyxiao opened 2 years ago

arlyxiao commented 2 years ago

当出现组件无限重新渲染时,会报如下错误

Uncaught Error: Too many re-renders.
React limits the number of renders
to prevent an infinite loop.

可能是由几种情况引起的

Updating the state inside the render
function App() {
  const [count, setCount] = useState(0);

  setCount(1); // infinite loop

  return
}

State updates → triggers re-render → state updates → triggers re-render → …

fixed

function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(1);
  }, [])

  return ...
}
Infinite loop in useEffect
function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(count + 1) // infinite loop
  }, [count])

  return ...
}

count updates → useEffect detects updated dependency → count updates → useEffect detects updated dependency → …

fixed

function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(previousCount => previousCount + 1)
  }, [])

  return ...
}
Incorrectly set event handlers
export default function App() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={setCount(1)}>Submit</button> // infinite loop
  );
}

State updates → triggers re-render → state updates → triggers re-render → …

fixed

export default function App() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(1)}>Submit</button> // infinite loop
  );
}

https://alexsidorenko.com/blog/react-infinite-loop/