In my React application I have a redux store that contains a user with the following model:
{
id: "",
name: "",
email: "",
isAdmin: false,
client: { id: undefined },
token: "",
tokenExpiry: null
};
On a simple page, I am querying a database for other data associated to that user. To do so I am taking advantage of the useEffect hook:
useEffect(() => {
// Check JWT auth token and refresh if near expiry
auth.refresh(
{ token: user.token, tokenExpiry: user.tokenExpiry },
// Request user "field" data
loadFields(user.client.id, user.token)
);
}, [user.client.id, user.token]);
Upon building, React presents the React Hook useEffect has missing dependencies: 'loadFields' and 'user.tokenExpiry'. Either include them or remove the dependency array warning.
If I understand useEffect correctly, the second parameter is the values which Reach will "watch", upon any change the component will be re-rendered (similar to how componentDidUpdate works)...
Whilst there are other values used within my useEffect call, I only want to reprocess this function when the user.client.id or user.token is changed. This is to avoid unnecessary re-renders when other parts of the user model is changed, so I don't want to add user.tokenExpiry as a dependency.
As the loadFields function is a function also used outside of from the useEffect logic, I cannot place it within useEffect so I've tried adding it as a dependency, but this causes a re-render loop as it has a dispatch call within it:
const loadFields = async (clientId, token) => {
setIsLoading(true);
try {
await dispatch(fetchFields(clientId, token));
setIsLoading(false);
} catch (error) {
setIsLoading(false);
dispatch(resetFields());
}
};
So what is the correct way to impelment useEffect in this scenario?
loadFiledsfunction - try to wrap it withReact.useCallbackhook like thisReact.useCallback(async (clientId, token) => { // ... }, []);and add it to dependency list. Accordinguser.tokenExpiryI can only think of a dirty hack: 1) create state withuser.tokenExpiryvalue, 2) createuseEffectthat updatestokenExpirystate on some condition, 3) add this state as a dependency to your existinguseEffect. But what is worse? This trick or a warning?:)useEffectas a dependency with an external script which utilisesuseEffect. I am also interested to know if it is possible to exclude dependencies without causing the warning (such as I've highlighted withuser.tokenExpiry).