Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to memo a function in react?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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
        }
    ]
}), []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading