React w/hooks: prevent re-rendering component with a function as prop

The current preferred route is useCallback, which is the same as your useMemo solution, but with additional possible optimizations in the future. Pass an empty array [] to make sure the function will always have the same reference for the lifetime of the component.

Here, you also want to use the functional state update form, to make sure the item is always being added based on the current state.

  const addItem = useCallback(() => {
    setItems(items => [...items, Math.random()]);
  }, []);

Leave a Comment