Using Context in React

Prerequisites

Before diving into useContext, you should be familiar with basic of JavaScript, and the basic concept of react such as props, state, hook.

Table of contents

  1. Prerequisites

  2. Introduction to React and useContext

  3. Benefits of Using Context

  4. How to Use Context in React

    1. Creating Context

    2. Providing Context

    3. Consuming Context

  5. conclusion

Introduction to React and useContext

The Context API allows developers to manage and share state across components without prop drilling. meaning you can pass data through the component tree without passing props down manually at every level. Context is useful for managing global state, such as user authentication, light/dark mode, or language settings.

In this article, we'll talk about useContext in React:- its benefits and how to implement it in your projects.

Benefits of Using Context

  1. Prop Drilling: Context helps in avoiding prop drilling, where you pass props through many components just to reach the one that needs the data.

  2. Code Readability: By centralising the state management, Context can make your code more readable and easier to maintain.

  3. State Management: For some global state, Context can simplify the management and propagation of state compared to more complex state management solutions, eg Redux.

How to Use Context in React

1. Creating Context

Firstly, you create a Context using React.createContext. This function returns an object with a Provider and Consumer.

import React from 'react';

const MyContext = React.createContext();

2. Providing Context

Next, wrap the component tree with Provider component. This component accepts a value prop, so it can be passed to the consuming components.

import React, { useState } from 'react';
import MyContext from './MyContext';

const App = () => {
  const [username, setUsername] = useState('Awwal');

  return (
    <MyContext.Provider value={{ username, setUsername }}>
      <MyComponent />
    </MyContext.Provider>
  );
};

export default App;

3. Consuming Context

The ways of to consume context in a function component is either using the useContext hook or the Consumercomponent.

Using useContext Hook

The useContext hook provides a simple way to access the context values.

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

const MyComponent = () => {
  const { username, setUsername } = useContext(MyContext);

  return (
    <div>
      <p>{username}</p>
      <button onClick={() => setUsername('Mario')}>Change Value</button>
    </div>
  );
};

export default MyComponent;

Using Consumer Component

Consumer component provides the render prop which help you access the context value.

import React from 'react';
import MyContext from './MyContext';

const MyComponent = () => (
  <MyContext.Consumer>
    {({ username, setUsername }) => (
      <div>
        <p>{value}</p>
        <button onClick={() => setValue('Ogunmepon')}>Change Value</button>
      </div>
    )}
  </MyContext.Consumer>
);

export default MyComponent;

4. Updating Context

The Context values can be updated using the state management techniques eg useState or useReducer. The updated value is then passed down to consuming components.

Example: Dark/Light mode Context

Let's look at a more practical example where we manage a theme context.

Creating Theme Context

import React, { createContext, useState } from 'react';

const ThemeContext = createContext();

export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light');

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};

export default ThemeContext;

Providing Theme Context

jsxCopy codeimport React from 'react';
import { ThemeProvider } from './ThemeContext';
import MyComponent from './MyComponent';

const App = () => (
  <ThemeProvider>
    <MyComponent />
  </ThemeProvider>
);

export default App;

Consuming Theme Context

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

const MyComponent = () => {
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    <div>
      <p>Current theme: {theme}</p>
      <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
        Toggle Theme
      </button>
    </div>
  );
};

export default MyComponent;

Conclusion

React Context is use for managing state across your application without the hassle of prop drilling. It is useful for global states like themes, authentication, and also language settings. Following the steps outlined in this article above can effectively help you understand and implement Context in your React projects. To improve your skills and boost your resume, consider applying for an internship program. The https://hng.tech/premium exactly the opportunity you need to gain real-world experience, work on exciting projects, and learn from industry professionals. This program is designed to help you build your skills, Improve your career & expand your network, and make your resume stand out.