React Context Api with Hooks to make Stateful Application

This blog is focused about to create a Stateful Application using React Context Api with Hooks. In this App we will Create a stateful app without using redux or any other third party library.

React Context Api used to share data in React component Tree. So we create Global State or Object to share the Data among Nth level of child and siblings under one root.

In This App we will create a theme changing demo where default theme will be passed from Our Top level Component and child component will be able to use that info. Also from child component we will be able to
update that top level theme data and immediately the update theme will reflect in subsequent child
components.

So lets get Started with following Steps to create a Stateful App using React Context Api with Hooks :

Step 1 : Creating a new React App using CRA, you may skip this if you already having React App setup.
To simply create & run a app named react-context-demo just use following statement in any your CLI

Now you have started the React App and it will look like this :

Step 2: Create a file named AppContext.js using following code :

Step 3: Go to App.js file and replace all code with following code :

Now you have App component in that we will import the provider from our created Context like this

now create a State for default theme like this :

Now wrap the Div ClassName App using Provider like this :

To use this default theme data we need to create 2 components, so we are creating 1 component to preview the theme and 1 component to update the theme

Step 4: Create a child component (Child.js) that uses the theme data and simply show a message with following code :

Now we need to call this component from App component, so returned jsx will look like this :

Lets see how the child component looks now after using the default theme :

Now there is 1 more Step that is required if we want to change the Theme Data/Global Data from any child component, so for that we will make another Toggle component.

Step 5 : Create a Toggle Component to change theme data to override Context Provider’s Default data Make a file named Toggle.Js and use following code in that :

Now Use this toggle component in App.js before/After the Child Component, We are calling it before so that it will look on top of child component like this :

Let see in Action How its looking.

Now we can see if we click on toggle button then we can easily switch the theme and that theme is also applying on child component immediately.

You may Download the complete source code by clicking this link. Please let me know your thoughts and improvement Ideas over this. Also if you face any kind of difficulties to run or understand that. Please let me know in comments section.

You may Download the complete source code by clicking this link