I get this 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
Here is a CodeSandBox example
The other answers work of course, I just wanted to share a solution I came up with. I built this hook that works just like React's useState, but will only setState if the component is mounted. I find it more elegant because you don't have to mess arround with an isMounted variable in your component !
npm install use-state-if-mounted
const [count, setCount] = useStateIfMounted(0);
You can find more advanced documentation on the npm page of the hook.