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?
First method is, You should learn first a Context APIs in react which already mentioned in docs https://reactjs.org/docs/context.html , use it for passing data between a screen. Second method is, Always call the API at parent level component, I think its a better and easier way.
To make the state change, React gives us a setState function that allows us to update the value of the state. Calling setState automatically re-renders the entire component and all its child components. We don't need to manually re-render as seen previously using the renderContent function.
Just remove the second useEffect and put your API call inside onChange function like this: For a better user experience and void unnecessary calls, you should add a loading state when the user clicks on the checkbox that gets disabled while fetching the result, then checked or unchecked based on the response.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With