Files
frontend-app-learning/src/user-messages/hooks.js
David Joy 65173e9f93 fix: remove conditions for an infinite React hooks loop (#81)
The useAlert hook was being given a new payload object every time it was called, defeating any memoization happening inside.

It was also re-calling it’s useEffect hook when alertId changed, which it was changing itself. That’s a no-no.
2020-06-10 17:08:07 -04:00

27 lines
774 B
JavaScript

/* eslint-disable import/prefer-default-export */
import { useContext, useState, useEffect } from 'react';
import UserMessagesContext from './UserMessagesContext';
export function useAlert(isVisible, {
code, text, topic, type, payload, dismissible,
}) {
const { add, remove } = useContext(UserMessagesContext);
const [alertId, setAlertId] = useState(null);
useEffect(() => {
if (isVisible && alertId === null) {
setAlertId(add({
code, text, topic, type, payload, dismissible,
}));
} else if (!isVisible && alertId !== null) {
remove(alertId);
setAlertId(null);
}
return () => {
if (alertId !== null) {
remove(alertId);
}
};
}, [isVisible, code, text, topic, type, dismissible, payload]);
}