React Context

Purpose

useContext is to not having to pass props into multiple children. So normally in order for our children to get the data from the parent, we need to pass the prop as following:

Pasted image 20230511160152.png

So something like

const ParentElement = () => {
	const data = "some data";
	<Children1 data={data}> </Children1>
}
const Children1 = ({ data }) => {
	<Children2 data={data}> </Children2>
}

And we have to do the same up to ChildrenN. However with useContext it's easier.

API

See also: https://react.dev/reference/react/useContext

// In parent element
const Context = createContext(defaultContext)

// In children component that has their parent inside Context.Provider
let value = useContext(Context)

The useContext will return a Provider and a Consumer:

  • Provider: we wrap the element that we want to share the context into this provider
  • Consumer: in previous version we use this to wrap the children element that we want to share the context to. The recent version we just use useContext

Note: In the Provider we need to provide props value={} for the default value and also the initial value that will be populate through out our children.

The defaultContext above will only be used for the children that's not being wrapped with the Provider

For example:

const DataContext = createContext("default data")

const ParentElement = () => {
	<DataContext.Provider value="initial value">
		<Children1/>
	</DataContext.Provider>

	// Inherit "default data"
	<Children4/>
}

const Children1 = () => {
	<Children2/>
}


const Children2 = () => {
	const data = useContext(DataContext) // initial value
	<Children3/>
}

const Children4 = () => {
	const data = useContext(DataContext) // default data
}

Legacy way

For useContext, we can do this, but it's not recommended

const Children = () => {
	<DataContext.Consumer>
		{ data => <> {data} </> }
	</DataContext.Consumer>
}