Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this react component rendering twice?

Tags:

reactjs

The problem is that the component is being rendered twice, once with the initial state, again after the setState method in axios promise. Why is this happening and how can I solve this.

I have used both componentWillMount and componentDidMount. I, being a noob, tried hard and failed to figure out why.

export default class Dashboard extends Component{

  constructor(props) {
    super(props)
    this.state = {
      data: {
        okay: 'lul'
      }
    }
  }

  componentWillMount() {
    axios
      .get('/api/data?param1='+this.props.location.state.param1+'&param2='+this.props.location.state.param2)
      .then(res => {
        if (res.status != 401) {
          if(res.err)
            console.log('Error while retrieving: ', res.err)
          else {
            this.setState({
              data: res.data.data
            })
          }
        } else {
          console.log('Unauthorized!');
        }
      })
  }

  render() {
    return (
        <Segment inverted vertical>
          <CardContainer data={this.state.data}/>
        </Segment>
    )
  }
}

Even basic suggestions related to react / JS / general programming is highly appreciated

like image 954
psvs Avatar asked May 02 '18 09:05

psvs


People also ask

Why is my React component rendering so many times?

This is because the React app component got re-rendered after the state values were modified, and it also re-rendered its child components.

How do you fix too many re renders in React?

What is this? The issue is that the setCounter function gets invoked when the component renders, updates the state, which causes a re-render and does that infinitely. You could solve the error by passing an initial value or a function to the useState() hook to initialize the state.

Why is functional component called twice?

Its because your app component is a wrap in StrictMode . It is expected that setState updaters will run twice in strict mode in development.

How to fix React components Render twice?

React Components render twice - any way to fix this? 1 A) Functional Component with useState. Removing the wrapper <React.StrictMode> will solve the problem in development... 2 B) Functional Component with useReduce. 3 C) Class Component. What is happening behind the scenes? The main reason is React.StrictMode which was introduced in... More ...

Why does react crash when I try to render something?

Some have even opened a bug report in the official React repository. The reason why this happens is an intentional feature of the React.StrictMode. It only happens in development mode and should help to find accidental side effects in the render phase. Let's find out if there is a way to avoid this problem by trying different implementations.

How to manage re-renders in react?

Let the re-renders to be managed by react. Even though the render function is getting invoked, there are sub components which doesn't gets refreshed on ui, if there is no props or state change inside it. Every setstate function call will inform react to check the diffing algorithm, and invoke the render function.

Why does react render with a similar functional component in strict mode?

Many developer have implemented a similar functional component and have seen this behavior. Some have even opened a bug report in the official React repository. The reason why this happens is an intentional feature of the React.StrictMode. It only happens in development mode and should help to find accidental side effects in the render phase.


1 Answers

You have a async request in componentWillMount, so before the request is completed, your component is rendered, however once the async request is successful you have a setState function call which triggers a re-render and hence your component is getting rendered twice

This is an expected behaviour.

You can check this question for more details

Use componentWillMount or componentDidMount lifecycle functions for async request in React

According to the docs

componentWillMount() is invoked just before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger an extra rendering.

This means that if you write

componentWillMount() {
   this.setState({count: 1});
}

the state will be reflected in the initial render itself and no-render is triggered. However if you have a async method then calling setState inside it might trigger an extra render if the async request gets completed after the render is already called.

To emphasize more on the fact, you must not use componentWillMount any more, since React is oncourse to remove this method from future major realease. Instead use componentDidMount.

like image 136
Shubham Khatri Avatar answered Oct 07 '22 06:10

Shubham Khatri