State Management in React: Making Sense of Context API

State Management in React: Making Sense of Context API

Let's Get Our Hands Dirty: Implementing Context API

Β·

3 min read

Alright, guys! Now that we understand what Context API is all about, let's roll up our sleeves and see it in action. Don't worry if you're new to this – we'll take it step by step, just like following a recipe for your favorite dish. 🍳

Step 1: Setting Up Our React Kitchen

First things first, let's create a new React project. If you already have one, great! If not, open your terminal and type

npx create-react-app context-api-demo
cd context-api-demo

This will create a new React app and move you into its directory. It's like setting up your kitchen before you start cooking!

Step 2: Creating Our First Context

Now, let's create our first context. Think of this as preparing a special container for our information.

Create a new file called ThemeContext.js in your src folder and add this code:

import React from 'react';

const ThemeContext = React.createContext('light');

export default ThemeContext;

Here, we're creating a context for our app's theme. We're saying that by default, our theme is 'light'. Easy peasy, right?

Step 3: Providing the Context

Next, we need to provide this context to our app. It's like putting our special container where everyone can reach it.

Open your App.js file and modify it like this

import React from 'react';
import ThemeContext from './ThemeContext';
import ThemedButton from './ThemedButton';

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <div className="App">
        <h1>Welcome to our themed app!</h1>
        <ThemedButton />
      </div>
    </ThemeContext.Provider>
  );
}

export default App;

Here, we're wrapping our app in a ThemeContext.Provider and setting the value to "dark". This means any component inside this provider can access this theme value.

Step 4: Consuming the Context

Now, let's create a component that uses this theme. Create a new file called ThemedButton.js

import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';

function ThemedButton() {
  const theme = useContext(ThemeContext);

  return (
    <button style={{ background: theme === 'light' ? '#fff' : '#000', 
                     color: theme === 'light' ? '#000' : '#fff' }}>
      I'm a {theme} themed button!
    </button>
  );
}

export default ThemedButton;

In this component, we're using the useContext hook to access our theme value. Then, we're using that value to style our button. Cool, right?

Step 5: See It in Action

Now, if you run your app (using npm start in your terminal), you should see a dark-themed button on your page. Try changing the value in the ThemeContext.Provider from "dark" to "light" in your App.js, and watch the button change!

What Did We Just Do?

Let’s recap…

  1. We created a context (our special container) for our theme.

  2. We provided this context at the top level of our app.

  3. We consumed this context in a child component.

And just like that, we've used Context API to manage a piece of state (our theme) across our app! πŸŽ‰

Wrapping Up

See? Context API isn't so scary after all! It's a powerful tool that can make your React apps much easier to manage, especially when you have data that needs to be accessed by many components.

Remember, like any tool, Context API isn't always the right solution. For simple apps or when you only need to pass data through one or two levels, props might still be your best bet. But when you find yourself passing the same props through multiple levels of components, it might be time to give Context API a try.

Keep experimenting, keep learning, and most importantly, keep having fun with React! Happy coding, everyone! πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

πŸ’‘
Follow me on 𝕏 @qzseeker
Β