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;
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.
// 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With