Effective use of Context in a React Application

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.


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!

React Redux – The art of state management

React is one of the most popular technologies for front-end development, which uses a component based approach to enable fast app development. Redux is a predictable state container for JS apps, and works particularly well with React.  In this article, I will be covering some basics on how to set up React-Redux for state management of a UI.

To illustrate the advantages of this approach, have a look at the UI structure shown below.

UI structure image 1

Let’s say the functionality required is that when a user interacts with the big component, the application has to update the small component and the header. In other words, we need to sync the header and small component as well as manage the states of all the other components. Without a state management library such as the one provided by Redux, coding this implementation can easily become very complicated.

Using the state functionality in React allows only the use of local, component level states.

Image 2

You can store the states using setState method, and fetch the stored state using state.[STATE_NAME]. However, these states are local, and only available within the class component in which it is declared.

Setstate image3

To store the states at the application level, i.e. the global level, in order to access them from different components, we can use React-Redux.

Let’s see how React-Redux works

You will see three main elements in the Redux architecture – Store, Dispatch Actions and Reducers.

Redux architecture 4

Store: holds the states at the application level, and allows any component to get data from the store in the form of Redux States.

Dispatch Action: a function of the Redux Store to trigger a state change.

Reducers: It handles the value change in Redux State.

How to configure React Redux in a React JS project –

The following packages are needed to be installed to configure  Redux in the project –

  1. Redux: the core package of React Redux.
  2. React-redux: needed for React bindings.
  3. Redux-thunk: a middleware which allows you to call action creators, and which returns a function instead of the action object.

These dependencies can be installed by using the following NPM command –
npm install redux react-redux redux-thunk –save

After these dependencies are installed, a store can be created and initialized with data/null values as per the requirements. This can be done by creating the file store.js in the project.

First however, you need to create reducer.js to handle the next states. Below is the example of reducer.js to initialize the state. Here, it is just returning the initial value from the reducer.

reducer.js 5

Below is a slightly more complex example of the code in reducer.js to update the states based on the action executed from the component.

coding 6

In the above example, it adds the data to the state upon the dispatch action (ADD_DATA). Now let’s create the action to dispatch. You can create a file with the name action.js, that contains the code shown below.

action.js 7

Once the action is created, now you can create a store and then connect the store to the application. You can create a file with the name store.js, that contains the code shown below.

store.js 8

To connect the store to the application, you will have to use the entry point. In the index.js (i.e. entry point of the app), import the store as shown below –

coding 9

These are all the Redux configurations for an application. Refer the the image below to use it in your component –

React component 10

React Redux can handle large amounts of data at the application level with cleaner components and is particularly useful for big applications.

Without Redux 11

With Redux 12

Without redux, to transfer data from component 1 to component 5, you need to pass it through middle components. This increases the props for components and creates more complexity and the components are less clean.

Using React-Redux, you can get or set the data to the store from any of the components directly by mapping the redux states to component props. In this case, you do not need to pass props to the middle components. This allows for much cleaner components and increased clarity in the code.

If you are looking to build a mobile or web application using React technology, then please feel free to contact us.

TypeScript in React

TypeScript is a useful technology for maintaining code quality and for self documentation of code in React. The use of “self-explanatory” code significantly reduces development cost and time. Typescript reduces the code analysis time and aids quick understanding of the existing implementation. This article serves as an overview for budding developers who wish to learn more about TypeScript.

Now, let’s understand – what is TypeScript?

TypeScript is an open-source programming language maintained and developed by Microsoft since 2012. It is a set of tools which uses a strongly typed, object-oriented and compiled language. It is an extended JavaScript programming language with additional features. When a new developer joins the team and uses any existing component of the project, he can easily understand its props with their specific types.

According to GitHub, TypeScript is one of the fastest-growing technologies. It is downloaded 31 Million times per month. Developer survey results of 2019 on stack overflow, place TypeScript at 10th position for “Most popular technology” and 3rd position for “Most Loved technology”. So as a new developer, it is not something which you can ignore.

When to use TypeScript?

Development teams working together on coding projects can struggle with code complexity, particularly as projects increase in size. TypeScript is recommended for large projects as it is the best option for maintaining code quality. It enables self-explanatory code right from the initial stages of the project.

Some of the significant features of TypeScript are listed below:

1. Static typing –
The static typing feature is one of the common reasons for developers to migrate their existing project from JavaScript to TypeScript. You can add data-types for variables, functions, properties, interfaces, etc, and it indicates warnings and errors regarding data type issues even before the compilation. I think that’s a wonderful feature because as a young developer, I faced a lot of problems while doing scripting.

static typing

static typing 2

Note: Static typing is optional.

2. Object-oriented –
TypeScript supports object-oriented programming, i.e. you can use class, Inheritance, Encapsulation, and Polymorphism.

3. Code suggestion –
It is best to use TypeScript with the IDEs since IDEs provide features such as IntelliSense and error highlighting.
If a developer wants to access the component props {this.props.}, then Typescript suggests all the available props, and highlights any typos.

Code suggestion

4. Display errors/warnings ASAP –
TypeScript highlights the errors immediately.

display error image 1

display error 2

5. TypeScript is portable –
All companies have a different kind of IT infrastructure set-up, with different operating systems and browsers. The advantage of TypeScript is that it is a superset of Javascript, meaning it can run on any environment that Javascript runs on. It is portable across operating systems and browsers.

How to create a new React JS project enabled by Typescript? –
To create a new project which is enabled by Typescript, you can use the following command.
e.g. npx create-react-app <> –TypeScript

It creates tsconfig.json which has typescript configurations.
“compilerOptions”: {
“target”: “es5”,
“lib”: [
“allowJs”: true,
“skipLibCheck”: true,
“esModuleInterop”: true,
“allowSyntheticDefaultImports”: true,
“strict”: true,
“forceConsistentCasingInFileNames”: true,
“module”: “esnext”,
“moduleResolution”: “node”,
“resolveJsonModule”: true,
“isolatedModules”: true,
“noEmit”: true,
“jsx”: “react”
“include”: [

Here, you can find the set of rules defined for the project. You can also modify or add more constraints if you want.

How to add TypeScript to the existing React JS project?
To add TypeScript in the existing project, you will have to install TypeScript and other required types externally
e.g. npm install –save TypeScript @types/node @types/react @types/jest @types/react-dom

After this, two changes are needed in the projects:
– First, rename all the “.js” file to “.ts” or “.tsx”
– Secondly, create a tsconfig.json in the root directory with the set of rules mentioned in the first step.

Happy Coding!!