Let's learn about useContext in React!(TIL)

March 16, 2024

Background

I saw use of useContext supported by React in my team project. It is more complicated than I think. useContext is used to implement modal UI. Its state which has value for open or close is managed by useContext. So, to understand it, I should learn about useContext.

Description

React DoC says,

useContext is a React Hook that lets you read and subscribe to context from your component.

And In addtion, I should notice its boundary to understand deeply. Context is the value had by any parent components. And any components including in parent component having context can access the value in its parent component. As you can see later, the Context Provier help it.

The advantages doing so can remove drilldowning props actually. Drilldowning props is passing props from parent component to child components being in deep side of their tree. So between parent component and child component, there can be many other components to pas props to target component. It would make your code messy.

Example

This example is reference React DoC!

// LevelContext.js
export const LevelContext = createContext(0);

// Heading.js
export default function Heading({ children }) {
	const level = useContext(LevelContext)

    return (
        <p className={`level-${level}`}>
            {children}
        </p>
    )
}

// Section.js
export default function Section({ children }) {
	return(
		<section className="section">
			<LevelContext.Provider value={level + 1}>
				{children}
			</LevelContext.Provier>
		</section>
	)
}

// Example.js
export default function Example(){
    return(
        <Section>
            <Heading>Hello World!</Heading>
            <Section>
                <Heading>This is Jimmy</Heading>
            </Section>
        </Section>
    )
}

This example is for implenting to display header having other size in each other deapth. As you can see above, just insert createContext function to create new Context. It is simple. And you must insert Provider in criteria where your components should get the value. Commonly, provider is located below the parent component including child component using the context value.

That's All!

Let's learn about useContext in React!(TIL)