How React.js Context works (TypeScript)

Daniel Babinszky
CodeX
Published in
4 min readJul 24, 2022

--

If your React application is constantly expanding, it will eventually reach a point when it needs global states. There are many solutions available; now, I’ll demonstrate the simplest one, which is intentionally developed in React: the React Context

Let’s imagine you or your customer wishes to upgrade an application to allow users to choose between light and dark modes. This implies that you must somehow provide each app component access to the actual theme information.

With a limited number of components in your application, you can use props for that

🏑 IN A SMALL APPLICATION YOU CAN PASS ANY INFORMATION WITH PROPS
const Navbar = () => {
const theme = useMemo(() => {
return props.theme
}, [])
return(
<div className={theme === 'light' ? 'light' : 'dark'}>
...
</div>
)
}
const Component = (props: { theme: string }) => {
const theme = useMemo(() => {
return props.theme
}, [])
return(
<div className={theme === 'light' ? 'light' : 'dark'}>
...
</div>
)
}
const Main = () => {
return(
<div>
<Navbar theme='light' />
<Component theme='light' />
</div>
)
}

You can do that, but it’s actually redundant and not at all encouraged. Not to mention what happens if you have many components on many different layers. In such instance, you must…

--

--