Skip to content

Commit 55fbf87

Browse files
committed
Prevent state update when component is unmounted in useDispatcher
1 parent f7f5ee0 commit 55fbf87

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

src/useDispatcher.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useContext, useState, useRef } from 'react';
1+
import { useContext, useState, useRef, useEffect } from 'react';
22
import TransporterContext from './TransporterContext';
33

44
const PENDING = 'pending';
@@ -27,9 +27,22 @@ export default function useDispatcher() {
2727
error: null,
2828
});
2929

30+
const mounted = useRef(false);
3031
const instances = useRef([]);
3132

33+
useEffect(() => {
34+
mounted.current = true;
35+
36+
return () => {
37+
mounted.current = false;
38+
};
39+
}, []);
40+
3241
const updateState = (instance) => {
42+
if (!mounted.current) {
43+
return;
44+
}
45+
3346
const latestInstance = getLatestInstance(instances);
3447

3548
if (latestInstance !== instance) {

0 commit comments

Comments
 (0)