Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context API react functional component

As I'm new to react I was searching for a way to use context api in my react app but couldn't find a way to use context api in functional component, most of them use it in class component. sorry for my question...

//this is my Context

    import React,{ createContext, Component } from 'react';
    export const ProductContext = createContext();
    class ProductContextProvider extends Component {
    state = {
        light: 'a',
        dark: 'b'
    }
    render() {
        return(
            <ProductContext.Provider value={{...this.state}}>
                {this.props.children}
            </ProductContext.Provider>
        );
    }
}

export default ProductContextProvider;
like image 318
ellie Avatar asked Sep 23 '19 06:09

ellie


2 Answers

With React 16.8, we got something called Hooks. Hooks allow developers to mimic class component functionality inside a functional component.

One of those hooks is the useContext hook which allows you to connect a functional component to a context.

const value = React.useContext(MyContext); 

From the documentation:

Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest <MyContext.Provider> above the calling component in the tree.

When the nearest <MyContext.Provider> above the component updates, this Hook will trigger a rerender with the latest context value passed to that MyContext provider.

like image 187
Rallen Avatar answered Sep 27 '22 22:09

Rallen


  // first define your context
  const MyContext = React.createContext();

  // wrap your component that should use the context
  <MyContext.Provider value={yourValue}>
    <YourComponent />
  </MyContext.Provider>

  // then inside YourComponent call useContext hook
  import {useContext} from React

  function YourComponent() {
    const contextValue = useContext(MyContext)
    return <div>{/* anything */}</div>
  }

Please refer to this link: https://reactjs.org/docs/context.html

like image 29
Lelouch Avatar answered Sep 27 '22 21:09

Lelouch