What I Want To Implement:
I am fairly new to the useCallback and useMemo React Hooks, and I'm still figuring out the correct use cases for each hook. Below is my component, which when props.orangeCountyCasesCityData changes, all of the values in the array are reduced into a total.
Can someone confirm this is the correct use of useCallback and also the correct use in the useEffect hook.
My Logic:
When
props.orangeCountyCasesCityDatachanges, theuseEffecthook is called.If the array length is greater than 1,
calculateTotalis called within theuseEffecthook.calculateTotaluses theuseCallbackhook, so that reduced value is memoized. Is this correct/am I missing anything?
Component (Current):
// React Hooks: Lifecycle Methods
useEffect(() => {
// Check If Data
if (props.orangeCountyCasesCityData.length >= 1) {
// All Cases Total
let allCasesTotal = props.orangeCountyCasesCityData.reduce((a, b) => a + b, 0);
// Set Total
setTotal(allCasesTotal);
}
}, [props.orangeCountyCasesCityData]);
Component (Correct Use Of useCallback?):
// React Hooks: Lifecycle Methods
useEffect(() => {
// Calculate Total
const calculateTotal = useCallback(() => {
// All Cases Total
let allCasesTotal = props.orangeCountyCasesCityData.reduce((a, b) => a + b, 0);
// Set Total
setTotal(allCasesTotal);
});
// Check If Data
if (props.orangeCountyCasesCityData.length >= 1) {
// Calculate Total
calculateTotal();
}
}, [props.orangeCountyCasesCityData]);
Component (useMemo):
// Total
const total = useMemo(() => {
// Check If Data Exists
if (props.orangeCountyCasesCityData.length >= 1) {
// All Cases Total
let allCasesTotal = props.orangeCountyCasesCityData.reduce((a, b) => a + b, 0);
return allCasesTotal;
}
}, [props.orangeCountyCasesCityData]);