How to avoid re-running useEffect with API call while using react-hot-loader?
Asked Answered
R

0

6

I'm using react-hot-loader in my local environment to develop my React + Firebase app.

For a basic component without API calls, I can see changes immediately (it only updates the changed part). But when I'm styling a component that has an API call inside a useEffect like the following example, it keeps re-running everything (including the effect) and I lose my current state.

The logs after I change something:

enter image description here

I'm not sure if the issue is because of the useEffect or the API call.

QUESTION

How can I fix this? Like, if I change the CSS color for a tag, I would like all my state to remain unchanged and update only the changed part.

Example:

ComponentWithApiCall.js

function ComponentWithAPICall() {

  const [loading,setLoading] = useState(true);
  const [dataFromAPI,setDataFromAPI] = useState(null);

  useEffect(()=>{

    // CALL API WAIT FOR RESULTS
    setDataFromAPI(result);
    setLoading(false);

  },[]);

  return(
    dataFromAPI &&
      <div>
        // WHATEVER
      </div>
  );
}

Here's my current configs for the react-hot-loader. I'm also using webpack and webpack-dev-server.

webpack.dev.js

  devServer: {
    contentBase: './public',
    compress: true,
    hot: true,
    historyApiFallback: true
  },

  plugins:[
    new webpack.HotModuleReplacementPlugin(),
    new webpack.HashedModuleIdsPlugin()
  ],

  resolve: {
    alias: {
      'react-dom': '@hot-loader/react-dom'
    }
  }

App.js

import { hot } from 'react-hot-loader/root';

// App component

export default hot(withRouter(App));    // I'M ALSO USING react-router
Rocha answered 28/11, 2019 at 10:25 Comment(1)
Did you ever resolve this issue?Tendon

© 2022 - 2024 — McMap. All rights reserved.