Introduction to React useContext

Hongtao Hao / 2023-06-10

The first step is to create the context, for example, UsernameContext.js:

import { createContext } from 'react';

const UsernameContext = createContext("");

export default UsernameContext;

The second step is (1) initiate the context values and (2) use the context provider. Note that this should be done at the parent level.

import { useState, useContext } from 'react';
import UsernameContext from './UsernameContext'

const [username, setUsername] = useState("")

return (
	<UsernameContext.Provider value={[username, setUsername]}>
		<ComponentA />
		<ComponentB />
	</UsernameContext.Provider>
)

The third step is to use the context in child components.

import { useState, useContext } from 'react';
import UsernameContext from './UsernameContext'

const [username, setUsername] = useContext(UsernameContext)

// do your tasks below using username and setUsername:

#react

Last modified on 2024-03-15