Context API technique using children
This describes a technique using children to avoid unnecessary re-renders when accessing React Context.
See code at https://codesandbox.io/p/sandbox/nostalgic-northcutt-s9hy5m?from-embed
Adapted from https://www.youtube.com/watch?v=16yMmAJSGek
Using this structure
└── src
├── App.css
├── App.js
└── contexts
└── CountContextProvider.js
The App.js
file contains
import { useContext } from 'react'
import CountContextProvider, { CountContext } from './contexts/CountContextProvider'
import './App.css'
export default function App() {
return (
<>
<CountContextProvider>
<Component1 />
<Component2 />
</CountContextProvider>
</>
)
}
const Component1 = () => {
console.log(`Component 1 renders`)
const { count, setCount } = useContext(CountContext)
return (
<>
<h3>Component ONE</h3>
<div>count = {count}</div>
<button onClick={() => setCount((prev) => prev + 1)}>[ + ]</button>
</>
)
}
const Component2 = () => {
console.log(`Component 2 renders`)
return (
<>
<h3>Component TWO</h3>
</>
)
}
and the contexts/CountContextProvider.js
file has the following:
import React, { createContext, useState } from 'react'
export const CountContext = createContext(null)
export default function CountContextProvider({ children }) {
const [count, setCount] = useState(0)
return (
<CountContext.Provider value={{ count, setCount }}>
{children}
</CountContext.Provider>
)
}