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?
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?
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.
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.