Gokul
Gokul

Reputation: 237

React -hook UseEffect memory Leak issue more than one function call

Hello Everyone I am new to react-hook I have some doubts about the useEffect call method

1 . I have one warning issue react Hook useEffect has a missing dependency "get data". Either include it or remove the dependency array react-hooks/exhaustive-deps I fixed that issue by using this command line // eslint-disable-next-line react-hooks/exhaustive-deps, if I am doing like this correct or not if any issue occurs in future production server.

  1. I have another issue in useEffect if I routing quickly I got this kind of error "Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function" I tried to search fix the problem I saw the answer in a single API call in the within inside useEffect, I have a more than one get API call how can I write a cleanup function, Any Ideas or Links

Thanks for Help

const [user,setUser]=useState([]);
const [post,setPost]=useState([]);

const UserList =()=>{
  axios.get("https://jsonplaceholder.typicode.com/users")
.then((res)=>{
  setUser(res.data)
 })
}

const PostList =()=>{
  axios.get("https://jsonplaceholder.typicode.com/post")
.then((res)=>{
  setPost(res.data)
 })
}

useEffect (()=>{
PostList();
UserList();
},[])

Upvotes: 1

Views: 2136

Answers (3)

Lokesh
Lokesh

Reputation: 301

Memory leaks happens when you try to set a state after your component is unmounted and this often happens when you set your state in async/promise functions.

One solution that I have been using for a while is initiating a variable outside component and check that variable before updating your state.

let isMounted = true;
const YourComponent = () => {
  const UserList = () => {
    axios.get("https://jsonplaceholder.typicode.com/users")
    .then((res)=>{
      if(isMounted){
        setUser(res.data)
      }
    })
  }

  useEffect(() => {
    UserList();
    return () => {
      isMounted = false;
    }
  }, []}
}

Upvotes: 1

Jaxoo Jack
Jaxoo Jack

Reputation: 70

after fetch data, need cleanup function. UseEffect(callback, deps) allows you to easily cleanup side-effects. When the callback function returns a function, React will use that as a cleanup function

useEffect(() => {
let controller = new AbortController();    (async () => {
  try {
   //fetch
  } catch (e) { 
    // Handle fetch error
  }
})();
return () => controller?.abort();  }, []);

obviously this is one option how you can deal with it

Upvotes: 0

user14361391
user14361391

Reputation:

Your API calls are not asynchronous, so the state is not updated until the API call is complete, but the components are rendered onto the screen which depends on the values of the state. Make your API calls async.

Upvotes: 1

Related Questions