4

I need to set state of a react component with values taken from the query parameters of the router/URL.

In which lifecycle method do I set the state with these params

constructor, componentDidMount, componentWillMount or any other?

Rahul Yadav
  • 1,651
  • 2
  • 17
  • 36

2 Answers2

0

The ideal lifecycle method to load data from a network request is componentDidMount

https://reactjs.org/docs/react-component.html#componentdidmount

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

Tom Nolan
  • 1,658
  • 4
  • 24
  • 44
  • I don't want to make network request just take parameters from the URL and set state. If URL params are available before component mount then why not set the state in the `constructor()` while state initialization itself or `componentWillMount()` – Rahul Yadav May 19 '18 at 11:10
0

According to official React docs, the recommended place to do Ajax requests or set state of a react component with values from URL params is in componentDidMount which is a lifecycle method that runs after the React component has been mounted to the DOM.

Fetch server data in the componentDidMount lifecycle method.

componentDidMount is where the magic happens. This method will be executed when the component “mounts” (is added to the DOM) for the first time. This method is only executed once during the component’s life.

Saurabh
  • 622
  • 4
  • 13
  • I don't want to make network request just take parameters from the URL and set state. If URL params are available before component mount then why not set the state in the `constructor()` while state initialization itself or `componentWillMount()` – Rahul Yadav May 19 '18 at 11:11