How To Execute Store.unsubscribe From Useeffect Using React Hooks And Redux
Solution 1:
If you set the second parameter of useEffect call to [], the effect callback function would act as ComponentDidMount. If that callback function returns a function, this function will be called just before the component is unmounted(ComponentWillUnmount).
And I guess this setState should be replaced with setItems as below. Please try this code.
const [items, setItems] = useState([]);
useEffect(() => {
setItems(store.getState().items.length);
const unsubscribe = store.subscribe(() => {
setItems(store.getState().items.length);
});
return unsubscribe;
}, []);
Solution 2:
Return a function from useEffect to do cleanup. So the returned function will be called when the component gets unmounted.
store.subscribe
return an unsubscribe function. Save its reference using useRef
hook and return the same reference from the useEffect
hook.
Read about it in the docs: https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup.
const storeRef = useRef(() => {});
useEffect(() => {
storeRef.current = store.subscribe(() => {
setState({
items: store.getState().items.length
});
});
return storeRef.current;
}, []);
useEffect(() => {
setState({
items: store.getState().items.length
});
return storeRef.current;
}, []);
Solution 3:
You shouldn't be using the store directly like that in the first place.
If you need to read values from the store as part of the component, you should use the React-Redux APIs that do that work for you: connect
and useSelector
. They already manage the work of subscribing and unsubscribing to the store as needed, so that your component can just specify what data it needs.
Post a Comment for "How To Execute Store.unsubscribe From Useeffect Using React Hooks And Redux"