Blog

Effective use of Context in a React Application

DATE:

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.

  1. Context ObjectThe Context object is designed to share data globally in the application.
  2. Context ProviderThe Context object comes with a provider that can be used to consume Context data in the React component.
  3. 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’.

Theme context object

2.Create the Theme object by using two Themes, for instance, here we are going to use ‘dark’ and ‘light’.

Create Theme Object

3.Create Theme Context provider.

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.

SubscribeThemeContext

6.Use or set the Context data as shown in the screenshot below.

Context data React

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!


TAGS:


MetaSys Software
Contact Contact
Covid Message