How to use Context API to pass down a state while using a Router in React JS

Asked
Active3 hr before
Viewed126 times

9 Answers

contextstateusingreact
90%

Connect and share knowledge within a single location that is structured and easy to search.,However in the ApiContext.js you aren't calling the API request properly. You should use useEffect to fetch the data only on the first render., Is it a correct to use passive voice in the following sentence?

In terms of the context itself, you don't have to change anything in your provider and only do something like this in the child components:

import React, {
   useContext
} from 'react'
import {
   ApiContext
} from './ApiContext'

const Dashboard = (props) => {
   const [data, setData] = useContext(ApiContext)

   //you should have access to both data and setData

   return (
      //things
   )
}

However in the ApiContext.js you aren't calling the API request properly. You should use useEffect to fetch the data only on the first render.

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

export const ApiContext = createContext();

export const ApiProvider = (props) => {
    const [data, setData] = useState(null);

    useEffect(async () => {
        const getURL = 'https://examplefetchsite.com';
        const response = await fetch(getURL).json();
        setData(response);
    }, [])

    return (
        <ApiContext.Provider value={[data, setData]}>
            {props.children}
        </ApiContext.Provider>
    );
}
load more v
88%

Next, we can create the AccountUpdate component that will be a basic form allowing the creation of a new username or change a membership level. This component will also need a small amount of internal state to handle on change and form submission events.,Voilà! On form submission, we are now updating the username and membership level dynamically, which, now appears with the new changes in the NavigationBar and AccountDetails components.,For the navigation bar, we need to create a stateless component called NavigationBar. This will display links to the home page and the account profile page.

Pretag
 Pretag team - issue, fix, solve, resolve
72%

By leveraging the Context API for this implementation, we’re able to create a flexible composition that is resilient to changes in structure.,Let’s take a look at how we can use the Context API to manage state and interactions across multiple components.,React’s Context API is a simple mechanism that allows you to easily share context between components, without directly passing props. If you’ve ever used React Router or Redux, you’ve used the Context API indirectly. While the Context API was previously considered unstable and was strongly discouraged for application development, all of that has changed with the release of React 16.3. Now, there is a simple, stable API, which means that we can use it in our applications!

First, we need to create a context:

const {
   Provider,
   Consumer
} = React.createContext("defaultValue");
load more v
65%

To use this provider, first, you will create your app's store using the initialState defined in the reducers.js file. Then, you will pass this store to your App with the help of Provider. To accomplish these tasks, you will have to open the index.js file and replace its contents with:,After a few seconds, create-react-app will have finished creating your app. So, after that, you can move into the new directory created by this tool and install Redux:,Therefore, you will need to create a providers.js file in the src directory and add the following code to it:

Pretag
 Pretag team - issue, fix, solve, resolve
75%

Using context, we can avoid passing props through intermediate elements:,Before You Use Context,If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context.

class App extends React.Component {
  render() {
    return <Toolbar theme="dark" />;
  }
}

function Toolbar(props) {
  // The Toolbar component must take an extra "theme" prop  // and pass it to the ThemedButton. This can become painful  // if every single button in the app needs to know the theme  // because it would have to be passed through all components.  return (
    <div>
      <ThemedButton theme={props.theme} />    </div>
  );
}

class ThemedButton extends React.Component {
  render() {
    return <Button theme={this.props.theme} />;
  }
}
load more v
40%

Among the changes in React 16.3 is a new stable version of the Context API. We’re going to take a look at how it works by building a protected route component.,Export a component AuthProvider to define our state (whether the user is logged in) and pass its state to the value prop on the Provider. We’ll simply expose AuthConsumer with a meaningful name.,Context Consumers must have a function as their direct child. This will be passed the value from our Provider.

To demonstrate Context’s basic functionality, let’s start by building a header component that lets us log in and out. First, create our context in a new file.

/* AuthContext.js */
load more v
22%

That’s where context comes in. You can declare the data in a common parent and then access later without explicitly passing it down the hierarchy of components.,Save and close the file. As with Navigation, it may seem unnecessary to create a context when the SaladSummary is in the same component as the context. Passing salad as a prop is perfectly reasonable, but you may end up refactoring it later. Using context here keeps the information together in a single place.,Since the user data will be constant across the project, put it as high up the component tree as you can. In this application, you will put it at the root level in the App component:

Pretag
 Pretag team - issue, fix, solve, resolve
60%

The state ("searchQuery") is actually what we need in the SearchResult.js component to filter out products or whatever.,Now you can use the "query" state and "searchHandler" function in any component inside the App component ,This makes a copy of the searchQuery state and stores it in the query variable defined in our little context.

// SearchBar.js

import React, { useState } from "react";
import { Link } from "react-router-dom";

import styles from "./SearchBar.module.css";
import SearchLogo from "../../assets/search.svg";

const SearchBar = (props) => {
  const [searchQuery, setSearchQuery] = useState("");

  return (
    <div className={styles.searchBar}>
      <input
        placeholder="Search"
        type="text"
        className={styles.input}
        onChange={(e) => setSearchQuery(e.target.value)}
        value={searchQuery}
      />
      <Link
        to="/search-result"
      >
        <img src={SearchLogo} alt="Search Logo | magnifying glass" />
      </Link>
    </div>
  );
};

export default SearchBar;
load more v
48%

In a typical React app, when a user executes an action and changes a component’s state, it may have an impact on the state of other components as well. This isn’t so bad when the app is simple. However, the more complex it grows, the more difficult it becomes to keep track of all the dependencies.,Reducer — Functions that take the current state of an application, perform an action, and return a new state.,We have reached the end of our application. The only needed part is to change the theme dynamically. For that, I used another component ThemeChanger.

To create a new React project with the TypeScript template, you can run:

npx create - react - app theme - changer--template typescript

or else

yarn create react - app theme - changer--template typescript

Install the react-router package and add types for typescript.

yarn add react - router - domyarn add @types / react - router - dom
load more v

Other "context-state" queries related to "How to use Context API to pass down a state while using a Router in React JS"