The prerequisite to comprehend this article is a fair knowledge of Hooks. Hooks is a new addition in React 16.8 that let you use state and other React features without writing a class.
In a React application, we can pass data from parent component to child components using the prop. However, this is limited to certain type of properties such as Theme, locale preference, etc., which need to be used at global level in the application. With React Context, we can use the data or props without explicitly passing them as props to the component.
Context has three main elements. We need to understand these elements to utilize Context to the fullest.
- Context Object – The Context object is designed to share data globally in the application.
- Context Provider – The Context object comes with a provider that can be used to consume Context data in the React component.
- Context Consumer – The Context Consumer is wrapped inside the Context provider, and it is used to get access to the Context data.
In this article, let us see how to create a Theme Context using typescript step by step.
1.Create Theme Context Object. Export ThemeContext and set the Context default value to ‘undefined’.
2.Create the Theme object by using two Themes, for instance, here we are going to use ‘dark’ and ‘light’.
3.Create Theme Context provider.
4.We created the Theme Context Provider by setting the Default Theme and function to change the Theme.
5.Subscribe Theme Context by wrapping the component with Context provider.
6.Use or set the Context data as shown in the screenshot below.
The concept of Context is simple yet effective. In this article, we covered how to use Context in the React Application with Theme Context example using TypeScript.
Should you have any queries, please contact MetaSys Software React experts, who have abundant experience in engineering applications using latest dev-tools such as React-Redux, React Hooks, React Router, React Bootstrap, etc.
You can reach out to us with any coding queries too! We would be happy to help!
Happy Coding!