React: Correct use of useCallback hook?

Viewed 279

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:

  1. When props.orangeCountyCasesCityData changes, the useEffect hook is called.

  2. If the array length is greater than 1, calculateTotal is called within the useEffect hook.

  3. calculateTotal uses the useCallback hook, 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]);
0 Answers
Related