I have simple setup with outlet and dynamic routes and on route change I want to fetch new data.
import React, { useEffect, useState } from 'react';
import { Link, Outlet, useParams } from 'react-router-dom';
export default function OutletContainer() {
const [apiResponse, setApiResponse] = useState(null);
let { outletComponentId } = useParams();
useEffect(() => {
// keeps api response state from previous route.
console.log(' ue inv id', apiResponse, outletComponentId);
fetch(
`https://anapioficeandfire.com/api/characters/${outletComponentId}`
).then((r) => setApiResponse(r.url));
return () => {
console.log('runcleanup');
setApiResponse(null);
};
}, [outletComponentId]);
return (
<div style={{ display: 'flex' }}>
<nav style={{ borderRight: 'solid 1px', padding: '1rem' }}>
{console.log('api', apiResponse, outletComponentId)}
<Link key={13} to={`/outletContainer/${13}`}>
13
</Link>{' '}
<Link key={12} to={`/outletContainer/${12}`}>
12
</Link>{' '}
<Link key={2} to={`/outletContainer/${2}`}>
2
</Link>
</nav>
<Outlet />
</div>
);
}
So, the problem:
When i swtich from /outletContainer/${12} to /outletContainer/${13}
console.log in useEffect keeps the apiResponse value from route 12 in route 13, even thou cleanup method in useEffect set apiResponse state null
return () => {
console.log('runcleanup');
setApiResponse(null);
};
My questions are:
1.Why is this happening? I was reading Dans blog post about useEffect but I got even more confused. Initial TLDR gave me hope, but down the road I got lost.

2.How to set state of a apiResponse to null each time i switch route.
You can check whole code on a stackblitz
