There’s basically 3 main things you need do to set up a shared state via useContext.
Determine the top level component you want to pass your context to. For my “Smarter Way to Learn X” case, it was the App component, because any other route beneath it would consume that state.
Create the context in its own file, and export it. This involves a simple 2 line code, in a ‘context’ folder of your app:
1
2
3
| import { createContext } from 'react'
export const TopicsContext = createContext(null)
|
- “Seed” the context around your parent component:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| import { TopicsContext } from '../contexts/TopicsContext'
export default function App({ Component, pageProps }: AppProps) {
const [topicsData, setTopicsData] = useState(null)
const topicsURL = 'http://localhost:3001/topics'
useEffect( () => {
axios.get(topicsURL)
.then(res => setTopicsData(res.data))
}, [])
return (
<TopicsContext.Provider value={topicsData} >
<Component {...pageProps} />
</TopicsContext.Provider>
)
}
|
In my case, I needed to fetch the data that will be the shared state first. The fetching is done at the top-most level.
- Finally, you can consume the context, wherever you need to!
1
2
3
4
5
6
| //TopicName.tsx page
import { TopicsContext } from '../../contexts/TopicsContext'
const TopicName = () => {
const topicsData = useContext(TopicsContext)
//topicsData will now be available.
|
Beautiful solution.