Home > front end >  How to memo a function in react?
How to memo a function in react?

Time:12-30

I am making an application using react and typescript and here I need to memoize a function.

  const formatData = (
    data: number[],
    gradientFill?: CanvasGradient
  ): Chart.ChartData => ({
    labels: ["a", "b", "c"],
    datasets: [
      {
        data
      }
    ]
  });

I have tried to memo the above function like,

  const formatData = useMemo((
    data: number[],
    gradientFill?: CanvasGradient
  ): Chart.ChartData => ({
    labels: ["a", "b", "c"],
    datasets: [
      {
        data
      }
    ]
  }),[]);

And this results in the following error.

Argument of type '(data: number[], gradientFill?: CanvasGradient | undefined) => Chart.ChartData' is not assignable to parameter of type '() => ChartData'.

Could you please help to properly implement useMemo to the above function? Thanks in advance.

Working example: (App.tsx file line no 10)

Edit Chart.js React Typescript (forked)

CodePudding user response:

useMemo's callback should not take arguments. Arguments should exist in the value returned from useMemo - the resulting formatData function.

const formatData = useMemo(() => (
    data: number[],
    gradientFill?: CanvasGradient
): Chart.ChartData => ({
    labels: ["a", "b", "c"],
    datasets: [
        {
            data
        }
    ]
}), []);

But useCallback would be more appropriate here.

const formatData = useCallback((
    data: number[],
    gradientFill?: CanvasGradient
): Chart.ChartData => ({
    labels: ["a", "b", "c"],
    datasets: [
        {
            data
        }
    ]
}), []);
  • Related