1

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)

1 Answer 1

1

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
        }
    ]
}), []);
Sign up to request clarification or add additional context in comments.

5 Comments

I have already tried useCallback but my team lead asked to memo the function instead of callback.
This is exactly the sort of situation useCallback was created for - to memoize a callback. While you can use useMemo to accomplish the same thing, it's odd (confusing - as evidenced by your question - useCallback doesn't have the same argument issue) and unnecessarily more verbose. useCallback is appropriate for all functions. useMemo is appropriate for everything else to be memoized that isn't a function.
Understood, Does the same statement apply for the another function canvasCallback as well? (Please take a look at the example in given question and there you can find it)
Yes, though since the inside of the canvasCallback depends on chartData, you'll want to add that to the dependency array when you memoize it with useCallback: useCallback(canvas: ....) => { ... }, [chartData]) Could be important just in case the props change
Okay understood and learned important things from your statement, thanks much bro.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.