Reputation: 3197
I need to make an API call on state change in react
Which lifecycle method should I put this API call in?
componentDidUpdate()
, getDerivedStateFromProps()
or any other?
What is the best practice?
Upvotes: 10
Views: 13029
Reputation: 904
You should be going for componentDidUpdate()
if it doesn't affect the state.
getDerivedStateFromProps()
mutates the state and therefore should only be used if your state relies on the nextProps
the component will receive. It won't fire on your state modifications but could be used combined with componentDidUpdate()
in a very few cases.
Here is a quick example using Redux of what you are willing to achieve, omitting on purpose actions, reducers and apis related files to avoid any confusion:
@connect(state => ({ searchResult: state.searchResult }))
class MassFetchingComponent extends React.Component {
state = {
search: '',
}
componentDidUpdate(prevProps, prevState) {
if (prevState.search!== this.state.search) {
dispatch(searchAction(this.state.search));
}
}
handleChange = search => this.setState({ search })
render() {
return (
<div>
<Input value={this.state.search} onChange={this.handleChange} />
{ this.props.searchResult }
</div>
)
}
}
I used an Input for the example purpose but I wouldn't recommend doing this if your state changes at a fast pace. Using sockets would be an option there.
Upvotes: 11
Reputation: 708
You should populate data with API call in the componentDidMount lifecycle method. This is so you can use setState to update your component when the data is retrieved.
Upvotes: -2
Reputation: 1304
You have two options:
componentDidMount
- good place for remote endpoint calls or subscriptions
componentDidUpdate
- good place for network requests "as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed)"
You may cancel or unsubscribe any lingering requests in componentWillUnmount
.
Upvotes: 0