Creating Dark theme using React hooks and context in Material UI

Ankit Brijwasi
Neurobit Technologies
2 min readJun 16, 2021

In this article, I will be showing you, how we can use React hooks and context to create dark theme in Material ui

What is Context?

In a typical React application, we can share data between components using props, however, As the application grows, and new components are added this method for sharing data between components becomes complex, and hard to manage.

To solve this problem React introduced Context. Context provides a way through which we can share data between components, without having to pass props to each component manually.

Creating the application

Open up the terminal and create a new react app, by using the following commands-

npx create-react-app myapp
cd myapp
yarn start

This will start the local react development server at http://localhost:3000

Installing the dependencies

install material ui using

yarn add @material-ui/core
yarn add @material-ui/icons

Creating the themes

Under the src folder create a new JavaScript file, called theme.js and paste the following code in it-

theme.js

Creating the Theme context

under the src folder create a new folder, hooks, inside this folder create a new JavaScript file, themeContext.js

This file will store all the code for managing the current theme.

Now paste the following the code in the themeContext.js file

themeContext.js

Now open up the index.js file, and paste the following code-

index.js

Now, to toggle the theme, We can create a Navbar component inside App.js and then, call the handleDarkMode function inside the Navbar.

App.js

Below is a gif, of how the final application looks

final application.gif

And that’s it, Hope you have a great day ahead!!

--

--

Ankit Brijwasi
Neurobit Technologies

Full stack developer at Neurobit. Python and JS are ❤️