The document discusses the useContext hook in React. It explains that hooks are special functions that start with "use" and are analogous to class component methods. The useContext hook allows components to access data from their parent context without having to pass props down through each level. Without useContext, data would need to be passed through props from the parent component to child components. With useContext, a Context Provider wraps components and provides a value that can be accessed using useContext in any child component without passing props.
Hooks ?
Hooks arespecial functions in functional react components, starting with the
pre
fi
x ‘use’.
These functions are analogous to various methods provided by react class
components
For example: we have useE
ff
ect hook which can mimic various react class
component life cycles like componentDidMount, componentDidUpdate.
We have useState analogous to react class component States.
3.
Without useContext Hook
component2
component 1
Props
component 3
component 4
Props
Props
function Component2(props) {
return <Component3 text={props.text} />;
}
function Component1(props) {
return <Component2 text={props.text} />;
}
function Component3(props) {
return <Component4 text={props.text} />;
}
function Component4(props) {
return <input type="text" value=
{props.text} />
}
4.
Using useContext Hook
component2
component 1
component 3
component 4
Context Provider Component
<contextObject.Provider value={<input
type="text" value={text}></input>}>
<Component1 />
</contextObject.Provider>
const value = React.useContext(contextObject);
<contextObject.Consumer>
{value=> <input type="text"
value={value}></input>}
</contextObject.Consumer>
For Consuming the data there are two methods