← react hacks / react / global-state-management-using-context-api.md

Implementing Context API for Global State Management in React

Learn how to manage global state in your React applications using the Context API. This tutorial includes code snippets for better understanding.

React’s Context API provides a way to pass data through the component tree without having to pass props down manually at every level.

First, create a context.

import React from 'react';
const MyContext = React.createContext(defaultValue);

Next, provide the context to the components that need it.

<MyContext.Provider value={/* some value */}>

Finally, consume it in your components.

class MyClassComponent extends React.Component {
  static contextType = MyContext;
  render() {
    return <div>{this.context}</div>; // value from MyContext.Provider
  }
}

Or in functional components, use the useContext Hook.

import React, { useContext } from 'react';
const value = useContext(MyContext);

Remember, Context API is designed to share data that can be considered “global” for a tree of React components, like the current authenticated user, theme, or preferred language.

Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  2. 8150376 Adding Event Handlers in JSX

    tag: reacttag: jsxtag: event handlers

  3. 2c098c3 Avoiding Unnecessary Re-renders with React.memo

    tag: reacttag: web developmenttag: performance optimization

  4. c2ffa3b Optimizing React Apps with useCallback

    tag: reacttag: useCallbacktag: optimization

00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?