Yes, React does free up memory used by states after they're no longer needed. When a component unmounts, React automatically cleans up any resources, including state, associated with that component. If the state is tied to a component, once the component is removed from the UI (unmounted), React's garbage collection process ensures that the memory used by the state is released, unless there are references to the state elsewhere (e.g., through closures or external objects).
To handle cleanup explicitly, you can use the useEffect hook with the return statement to clean up resources when a component is unmounted or before the effect is re-run.
Example:
import { useEffect, useState } from "react";
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => setCount(prevCount => prevCount + 1), 1000);
return () => clearInterval(timer); // Cleanup timer when component unmounts
}, []);
return <div>{count}</div>;
}