React: Where to put API call to be made on state change

react lifecycle diagram
react on props change
reactjs api call example
react api service class
react hooks api
react get request
react state management
api call on state change react

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?

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.

Where to put api call to trigger it every time state changes , My goal is to call api based on state change, Every time state changes, I want the api call triggered. MyComponent import * as React from  As explained in the previous section, React intentionally “waits” until all components call setState () in their event handlers before starting to re-render. This boosts performance by avoiding unnecessary re-renders. However, you might still be wondering why React doesn’t just update this.state immediately without re-rendering.

Fetching Data and Updating State in a React Class, Fetching Data and Updating State in a React Class When the component loads​, I need it to create a request to my REST API Component { componentDidMount() { // make fetch request } componentWillUnmount() { // make fetch request } The componentDidMount method is a great place to request data  In general, you should initialize state in the constructor, and then call setState when you want to change it. For example, let's say we want to make text that blinks all the time. The text itself gets set once when the blinking component gets created, so the text itself is a prop .

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.

enter link description here

React Updating State, We call ReactDOM.render() to change the rendered output: function tick() To implement this, we need to add “state” to the Clock component. State is similar to​  Of course, application UIs are dynamic and change over time. That’s why state was created. State allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule. Components defined as classes have some additional features. Local state is a feature available only to class Components.

React Lifecycle Methods- how and when to use them, Example: Using AJAX results to set local state. The component below demonstrates how to make an AJAX call in componentDidMount to populate local  In the React sense, “state” is an object that represents the parts of the app that can change. Each component can maintain its own state, which lives in an object called this.state . Simply put, if you’d like your app to do anything – if you want interactivity, adding and deleting things, logging in and out – that will involve state.

State and Lifecycle – React, When state changes, the component responds by re-rendering. Calls to setState are asynchronous - don't rely on this.state to reflect the new value you need to compute values based on the current state (see below for details). InstallationMain ConceptsAdvanced GuidesAPI ReferenceHooksTesting​Concurrent Mode  Thanks to the setState () call, React knows the state has changed, and calls the render () method again to learn what should be on the screen. This time, this.state.date in the render () method will be different, and so the render output will include the updated time. React updates the DOM accordingly.

AJAX and APIs – React, Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable. Edit this page. There is an API built, and I want to be able to make REST calls -- GET, POST, PUT, DELETE -- from the client-side. How and what is the properly way to go about doing so with the Redux architecture? Any good example of the flow, in terms of reducers, action creators, store, and react routes, would be extremely helpful.

Comments
  • If you may elaborate how to do this "You may cancel or unsubscribe any lingering requests in componentWillUnmount."
  • @Rahul It's API-specific. For example if you do api.endpoint.subscribe() in componentDidMount, then you'd call api.endpoint.unsubscribe() in componentWillMount.
  • I agree that componentDidMount should be used to fetch your initial data but I don't think this is the point here. He is willing to make an api call anytime the state changes.