Redundant Piece Of Code Using React Hooks
There's a fixed number of settings that determine whether the component should be visible, i.e.: const restrictions = { isLogged: true, // TRUE stands for: check if the condition
Solution 1:
I'd refactor a single atom into a custom useRestrictionState
atom that internally deals with the effect:
const restrictions = {
isLogged: true, // TRUE stands for: check if the condition is methasMoney: true,
didWinYesterday: false,
};
functionuseRestrictionState(restrictionFlag, apiFunc) {
const [flag, setFlag] = React.useState(undefined);
useEffect(() => {
if (!restrictionFlag) {
setFlag(true);
} else {
apiFunc().then((result) =>setFlag(result));
}
}, [restrictionFlag]);
return flag;
}
functionComponent() {
const isUserLogged = useRestrictionState(restrictions.isLogged, getLoginState);
const hasUserMoney = useRestrictionState(restrictions.hasMoney, getUserMoney);
const didUserWinYday = useRestrictionState(restrictions.didWinYesterday, getUserDidWinYesterday);
}
If you always need all of them, you can naturally wrap this in another custom hook:
functionuseUserRestrictionState(restrictions) {
const isUserLogged = useRestrictionState(restrictions.isLogged, getLoginState);
const hasUserMoney = useRestrictionState(restrictions.hasMoney, getUserMoney);
const didUserWinYday = useRestrictionState(restrictions.didWinYesterday, getUserDidWinYesterday);
return { isUserLogged, hasUserMoney, didUserWinYday };
}
functionComponent() {
const { isUserLogged, hasUserMoney, didUserWinYday } = useUserRestrictionState(restrictions);
}
Solution 2:
Here's my take:
import { useState, useEffect } from'react'const useCheck = (condition: boolean, performCheck: () => boolean): boolean => {
const [isConditionMet, setIsConditionMet] = useState<boolean>(false)
useEffect(() => {
const check = async () => {
const isConditionMet = awaitperformCheck()
setIsConditionMet(isConditionMet)
}
if (!condition) {
setIsConditionMet(true)
}
check()
}, [condition, performCheck])
return isConditionMet
}
exportdefault useCheck
Usage:
const isUserLogged = useCheck(restrictions.isLogged, () =>true) // 2nd parameter should be an API call in my case
Post a Comment for "Redundant Piece Of Code Using React Hooks"