How does React Context work by using a function inside of a component

Asked
Active3 hr before
Viewed126 times

10 Answers

functionusingcomponentreact
90%

Context provides a way to pass data through the component tree without having to pass props down manually at every level.,If two or more context values are often used together, you might want to consider creating your own render prop component that provides both.,One way to solve this issue without context is to pass down the Avatar component itself so that the intermediate components don’t need to know about the user or avatarSize props:

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
88%

React Functions as Child Components,So if I'm getting this right, you are basically asking how you could get a component which is in the following format:,How does this code work ? How can a function be called inside a component?

So if I'm getting this right, you are basically asking how you could get a component which is in the following format:

<MyComponent>
  {(name) => (
    <div>{name}</div>
  )}
</MyComponent>

So your MyComponent component will look something as follows:

class MyComponent extends React.Component { 
  render() {
    return (
      <div>
        {this.props.children('Scuba Steve')}
      </div>
    );
  }
}
MyComponent.propTypes = {
  children: React.PropTypes.func.isRequired,
};
load more v
72%

This new API solves one major problem–prop drilling. Even if you’re not familiar with the term, if you’ve worked on a React.js app, it has probably happened to you. Prop drilling is the processing of getting data from component A to component Z by passing it through multiple layers of intermediary React components. Component will receive props indirectly and you, the React Developer will have to ensure everything works out right.,React's context allows you to share information to any component, by storing it in a central place and allowing access to any component that requests it (usually you are only able to pass data from parent to child via props).,What did we forget? The ProductList! This is where the benefit becomes apparent. We don’t pass any data or methods. The component is simplified because it only needs to render a few components.

App.js

class App extends Component {
    state = {
        cars: {
            car001: { name: 'Honda', price: 100 },
            car002: { name: 'BMW', price: 150 },
            car003: { name: 'Mercedes', price: 200 }
        }
    };
    incrementCarPrice = this.incrementCarPrice.bind(this);
    decrementCarPrice = this.decrementCarPrice.bind(this);

    incrementCarPrice(selectedID) {
        // a simple method that manipulates the state
        const cars = Object.assign({}, this.state.cars);
        cars[selectedID].price = cars[selectedID].price + 1;
        this.setState({
            cars
        });
    }

    decrementCarPrice(selectedID) {
        // a simple method that manipulates the state
        const cars = Object.assign({}, this.state.cars);
        cars[selectedID].price = cars[selectedID].price - 1;
        this.setState({
            cars
        });
    }

    render() {
        return (
            <div className="App">
                <header className="App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <h1 className="App-title">Welcome to my web store</h1>
                </header>
                {/* Pass props twice */}
                <ProductList
                    cars={this.state.cars}
                    incrementCarPrice={this.incrementCarPrice}
                    decrementCarPrice={this.decrementCarPrice}
                />
            </div>
        );
    }
}
load more v
65%

When to use the Context API;,Here is what consuming our ThemeContext with a functional component would look like:,Those are the two methods of consuming context with class-based components.

import React, { Component } from "react";
import ThemeContext from "../Context/ThemeContext";
import AppTheme from "../Colors";

class Main extends Component{
    constructor(){
        super();
    }
    static contextType = ThemeContext;
    render(){
        const currentTheme = AppTheme[this.context];
        return(
            <main></main>
        );
    }

}
render() {
        const currentTheme = AppTheme[this.context];
        return (
            <main style={{
                padding: "1rem",
                backgroundColor: `${currentTheme.backgroundColor}`,
                color: `${currentTheme.textColor}`,

            }}>
                <h1>Heading 1</h1>
                <p>This is a paragraph</p>
                <button> This is a button</button>
            </main>
load more v
75%

createContext() method is used to create a context. We can also pass the default value to the context variable by passing it to the createContext(). ,In the Functional component, we are accessing context with the help of the useContext method.,Access Context in functional component by using useContext method of React.

 

import React, { Component } from "react";

import ReactDOM from "react-dom";

import UserProfile from "./UserProfile.js";


class App extends Component {

 constructor(props) {

   super(props);

   this.state = {

     currentUser: ""

   };

 }


 render() {

   return (

     <div>

       <UserProfile currentUser={this.state.currentUser} />

     </div>

   );

 }

}


const rootElement = document.getElementById("root");

ReactDOM.render(<App />, rootElement);
load more v
40%

Ok, let's continue. For this context module to be useful at all we need to use the Provider and expose a component that provides a value. Our component will be used like this:,But I think that's a missed opportunity at providing a better user experience. Instead, I think it should be like this:,How to create and expose React Context providers and consumers

.css - qnqv84 {
   display: inline - block;width: 2 em; - webkit - user - select: none; - moz - user - select: none; - ms - user - select: none;user - select: none;opacity: 0.3;
}
1 // src/count-context.js2import * as React from 'react'34const CountContext = React.createContext()
load more v
22%

Ideally, a function’s arguments are used for its operation.,With components, these arguments are called props. Props (short for properties) are object arguments. An ErrorMessage can look something like:,The receiving components are TopNav and Profile

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

To start with the Context API, the first thing we need to do is create a context using the createContext function from React.,After creating your context, that context now has two React components that are going to be used: Provider and Consumer.,The createContext function accepts an initial value, but this initial value is not required.

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

The context API is a powerful tool for creating shared state between multiple components. It’s a great way of avoiding coupling and your components together, which makes them easier to test and maintain.,Instead of passing the counter prop into ChildComponent, we can use the React Context API to share the counter state between both components. Here’s how:,The biggest difference between the context API and useState() is that the context API allows you to share state between multiple components at once. The useState() hook is scoped to a single component only.

import React from 'react'

const ParentComponent = () => {
    const [counter, setCounter] = React.useState(0)

    return (
        <ChildComponent
            counter={counter}
            onIncrement={() => setCounter(counter + 1)}
        />
    )
}

const ChildComponent = ({ counter, onIncrement }) => {
    return (
        <div>
            {counter}
            <button onClick={onIncrement}>increment</button>
        </div>
    )
}
load more v
23%

Above we added our Consumer, in the form of Theme.Consumer component and we can see that we inside it define a function whose parameter is our theme value. We are then able to show the theme value in a div.,So next up is about declaring a Consumer component and show how we can show the value to the user. Let’s add that to our code:,declare a consumer, this is also a component that lives on the Context object and we use this to show the value to the user

npx create - react - app context - demo
cd context - demo
npm start
load more v

Other "function-using" queries related to "How does React Context work by using a function inside of a component"