简体   繁体   中英

Why useState hook causes unnecessarily re-render cycle in React?

Why does just defining the state like this:

const [flipCardDeg, changeFCDeg] = useState(0);

in a normal function component cause an additional re-render cycle? Instead of 1 re-render, it re-renders twice.

I know that if somewhere is used "changeFCDeg" to change the state it should re-render, that's OK. But why at the beginning, when initializing everything, it re-renders one more time?

Should I worry about having 2 re-renders instead of one, and if yes, how to deal with it?

React re-renders whenever it detects change. You can try to get control over that by specifying exactly what it perceives as a change. For example, like this:

const getMoreData = false
const [flipCardDeg, changeFCDeg] = useState(0);
useEffect(() => {
  console.log('say something once')
  return () => {
    console.log('why say it again?')
  }
}, [getMoreData])  // will only run once unless getMoreData is changed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM