DEV Community

Cover image for How to use the Context API, What is Context API?
Natnael Birhanu
Natnael Birhanu

Posted on

How to use the Context API, What is Context API?

this post is written for someone who want to understand in simple terms what the Context API is and how to fit it in your app to make your life better.

The gist of it is prop drilling bad, prop drilling messy, prop drilling boring, prop drilling not classy, did i say prop drilling bad? anyway. so just have a slick way to manage your state(data).

Context API

Problem: Passing state down through multiple levels of a component tree can quickly become cumbersome and inconvenient, just bad bad bad, a problem known as prop drilling(duh!).

Solution:The React Context API allows you to pass state from a parent component into a deeply nested child component without having to manually pass props down the component tree.

how does it do it? magic lol.

Anyway, it just give you a way to subscribe to a CONTEXT(am sure you didn't see that coming). meaning it lets you create a context that some components subscribe to and some other parent component provides.

How it works:
The Context API has three main components:

  1. Context object: An object that represents the context and is used to create the provider and consumer components.
  2. Consumer: A React component that reads the value from a provider.
  3. Provider: A special React component that gives all child components access to a so-called value.

To use the Context API, you first need to create a context object using the createContext() function. This function takes an optional default value for the context, which will be used if a component does not have a matching provider above it in the component tree.

Once you have created a context object, you can then create provider and consumer components. The provider component takes the context value as a prop and wraps all of the components that need access to the context state. The consumer component uses useContext(SomeContext) to access the state.

When a component is subscribed to a context, it will be re-rendered whenever the context value changes. This means that you can easily keep your components up-to-date with the latest state without having to manually pass props down the component tree.

Think of it like Theo is screaming all day on twitter to give you the worst takes ever, but if you are not his follower/under him pause, you can't access it(thank God), so when he broadcast his takes and you happen to be following him you will have access to it(ugh poor you), but you still can not see it unless you specifically interact with it(i hope).

so am sure you are expecting code, so here is what chatGPT responded with,


const ThemeContext = createContext({
  theme: "light",
}); 
// Let's say you want some theming state, so you create a
// context object( using createContext()),you can
// provide default values, think of it like useState here.


function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("light");

// you can do some operations here on the state
// like updates and stuff

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}
// then create a provider component, that gives and manipulates
// the data if you want it to change on some event or stuff. 
// it should accept a 'children' prop(how ironic huh? prop bad) 
// so that it wraps all the components that want to
// subscribe to this context( can have access to this state).

function useTheme() {
  const context = useContext(ThemeContext);
  if (context === undefined)
    throw new Error("no no, subscribe to my YouTube 
channel first to use my data");
  return context;
}
// Pro Tip: create a custom hook so you won't have to 
// always say useContext(ThemeContext), just say 
// useSomeCoolCustomHookName();.


export { ThemeProvider, useTheme};
//then ship it 

// all this should be in like some contexts folder and
// ThemeContext.jsx file or something





// Create a consumer component(file) that use the state.
function ThemeConsumer() {
  const { theme } = useTheme();  
// you would have to use 
// useContext(ThemeContext); if it weren't for me


  return <div style={{ color: theme }}>your app content and components ...</div>;
}




function App() {
  return (
    <ThemeProvider>
      <ThemeConsumer />
    </ThemeProvider>
  );
}
// just wrap all the components that need this context with the context provider.
Enter fullscreen mode Exit fullscreen mode

if you are serious and want to use the Context API? just read the docs bro always just read the docs bro, it took me 30 minutes to rant and edit all this shit please laugh.

Top comments (0)