DEV Community

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

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