0

I have some question in react. It's not a big problem, but I don't understand.

I make a components where new data is continuously added to data. It makes sense that two console logs appear at first. Because of Mount and Update. But next cycle, here is my question.Why do 4 console logs appear? and then 8.. and then 16.. and then 32 .......

here is the code.

import React, { useState } from 'react'

const Ex = () => {
    const [state, setstate] = useState({ test: 'data' })
    const handleDate = () => {
        const { test } = state
        const data = 'new data'
        setstate({ test: test + data })
        console.log(`test: ${test}`);
    }
    setTimeout(handleDate, 3000);
    return (
        <div>
            <span>Result: {state.test}</span>
        </div>
    )
}

export default Ex
  • 1
    I don't think you should be using `setTimeout` to call back into your code like that - you should dispatch an action instead. When you use `setTimeout` the callback occurs outside of React's control of the DOM, which explains why you're seeing strange results. – Dai May 25 '21 at 02:57
  • Why are you calling `setTimeout()` in a render function? What is the behavior you want for `handleDate()`? – Han Seoul-Oh May 25 '21 at 03:30

1 Answers1

0

It would seem that every time state changes, your component is rendered twice, for whatever reason best known to React. Now each time it renders, it calls setTimeout to trigger a state change in 3 seconds. Each of those changes triggers two more renders, which in turn generate two more setTimeouts, each of which will cause the component to render twice again, and so on and so forth.

Rather than having a setTimeout inside the render, you should use the useEffect hook to achieve the result you want, namely a self-updating component. See this answer: React hooks - right way to clear timeouts and intervals

see sharper
  • 11,505
  • 8
  • 46
  • 65