1

I am a bit confused about what's the proper way to use useMemo. Reading here (Should I wrap every prop with useCallback or useMemo, when to use this hooks?) it says that I have to use it for expensive children, so what does that mean exactly? Can someone provide a real life example?

I created a new React project playing around with 2 different approaches.

You can check the full code here (in the same page you can switch from one method to the other):

https://codesandbox.io/s/lucid-rgb-fz60n

In this first example I pass to AppContext an object containing userState and setUserState (logged or not).

  const [userState, setUserState] = React.useReducer(reducer, initialUserState);

  const appState = {
    userState,
    setUserState
  }

  <AppContext.Provider value={appState}>

Would this approach be acceptable?

In the second example, I use useMemo:

const [userState, setUserState] = React.useReducer(reducer, initialUserState);

  const value = React.useMemo(() => {
    return {
      userState,
      setUserState
    };
  }, [userState]);

<AppContext.Provider value={value}>

So I suppose that useMemo in this second case it's not a good choice since the children is not expensive. Is this correct?

devamat
  • 2,293
  • 6
  • 27
  • 50
  • You also need to consider that, if `userState` is unchanged, everything that consumes `AppContext` will re-render unnecessarily because `appState` is a different reference on every render. So `useMemo()` will prevent that. – Patrick Roberts Oct 13 '19 at 06:00
  • What does exactly mean "everything that consumes AppContext"? – devamat Oct 13 '19 at 06:31
  • As in every occurence of [``](https://reactjs.org/docs/context.html#contextconsumer) in the component hierarchy... – Patrick Roberts Oct 13 '19 at 06:36
  • In my code I'm not using ``. In the child component I have `const value = React.useContext(AppContext);` and `const value = React.useContext(AppContext);` is it the same? – devamat Oct 13 '19 at 06:49
  • Yes `useContext()` accomplishes the same. – Patrick Roberts Oct 13 '19 at 06:57

0 Answers0