atlaschiew / react-study

happy reacting
0 stars 0 forks source link

componentDidMount() triggered twice, why? #10

Open atlaschiew opened 1 year ago

atlaschiew commented 1 year ago

This is answer from chatGPT

In React, componentDidMount is a lifecycle method that is called once, immediately after a component is mounted (inserted into the DOM).

If you are observing componentDidMount being triggered twice, it is likely because the component is being rendered twice. There are several reasons why this might be happening:

1) Initial render and re-render: The first time a component is rendered, it triggers componentDidMount. However, if the component is re-rendered due to a state or props change, it will trigger componentDidMount again.

2) Render methods in higher-order components: If your component is wrapped in a higher-order component that has its own render method, this can cause your component to be rendered twice.

3) DevTools and strict mode: If you are using the React DevTools, it can sometimes trigger a "double-render" in strict mode, which will cause componentDidMount to be called twice.

atlaschiew commented 1 year ago

In my case, number 3 is root cause of my problem.