DEV Community

Discussion on: React Context API: updating Context from a nested component (in functional components with Hooks and class components)

Collapse
 
cyrfer profile image
John Grant

Your example is the only way I know how to update the context from a child.

      <VideoContext.Provider
        value={{
          status,
          togglePlayPause,
        }}
      >
Enter fullscreen mode Exit fullscreen mode

Unfortunately, making a new object each time the Provider is rendered is specifically warned about here,
reactjs.org/docs/context.html#caveats

I'm starting to think React documentation warns, but the design does not offer a solution, and you must live with the side effects of their warning - that all consumers will be re-rendered.

Collapse
 
veryspry profile image
Matt Ehlinger • Edited

I noticed this too - you can use React.useMemo to create a memoized value object. That way the object is only updated when one of its dependencies updates and then avoid rerendering all consumer component trees so many times.

  const [status, setStatus] = useState('paused');
  const togglePlayPause = () => setStatus(status === 'playing' ? 'paused' : 'playing');
  const contextValue = useMemo(() => ({ status, togglePlayPause }), [status, togglePlayPause])
Enter fullscreen mode Exit fullscreen mode