useTheme Custom Hook: Maintain Standard Theme throughout the app
Tags: react, hooks, ux
Published: 2022-12-14 11:09:13


While working on a project, I found myself needing to use the same theme throughout the app. I wanted to be able to change the theme in one place and have it update everywhere. Also I don't want to remember the color codes of theme used in app.

To get rid of this problem, I created a custom React Hook `useTheme`. This hook will return the theme object and a function to update the theme. The theme object will be updated in all the components that use this hook.

Will cover this in detail with 3 main parts:

1. Theme Object
2. Custom Hook
3. Usage

<hr>

## 1. Theme Object

The theme object will have the following properties:

#### 1. Colors

- `primaryColor`
- `secondaryColor`
- `backgroundColor`
- `borderColor`

#### 2. Current Theme

- `dark` or `light`

#### 3. Toggle Theme Function

- This function will `toggle` the theme between dark and light

> NOTE: These 3 properties is just for an example. You can add more properties to the theme object.

The theme object will be updated in all the components using this hook. So, the theme will be maintained throughout the app. **These will ensure that the theme is consistent throughout the app.**


```js
const lightColors = {
    primary: '#101010',
    secondary: '#7f7f7f',
    background: '#efefef',
    border: '#303030',
}

const darkColors = {
    primary: '#efefef',
    secondary: '#7f7f7f',
    background: '#101010',
    border: '#b0b0b0',
}
```
<hr>
## 2. Custom Hook

React hooks are functions that let you hook into React state and lifecycle features from function components. You can read more about React Hooks [here](https://reactjs.org/docs/hooks-intro.html).

You can create a custom hook by using the `use` prefix and the name of the hook. For example, here `useTheme` is a custom hook. The custom hook will return the theme object and a function to update the theme. Here is the code for the custom hook:

```js
const useTheme = () => {
	const [theme, setTheme] = useState('dark')

	const toggleTheme = () => {
		const nextTheme = theme === 'dark' ? 'light' : 'dark'
		setTheme(nextTheme)
	}

	const colors = theme === 'dark' ? darkColors : lightColors

	return { colors, currentTheme: theme, toggleTheme }
}
```
<hr>

## 3. Usage

Now, we can use this custom hook in any functional component. Here is an example of how to use this hook in an `App` component:

```js
import React from 'react'
import { useTheme } from './useTheme'

const App = () => {
        // get required properties from hook
	const { colors, currentTheme, toggleTheme } = useTheme()

	return (
		<div
			style={{
				backgroundColor: colors.background,
				color: colors.primary,
				padding: '1rem',
			}}
		>
			<h1>Custom Hook</h1>
			<p>Current Theme: {currentTheme}</p>
			<button onClick={toggleTheme}>Toggle Theme</button>
		</div>
	)
}
```

<hr>

## Found Interesting? Try it out!  👨‍💻

You can try out the `useTheme` hook implementation in this [CodeSandbox](https://codesandbox.io/s/autumn-worker-8gt77e).

<hr>

## Complete Code

Here is the complete code for the custom hook for your reference:

```js
import { useState } from 'react'

const lightColors = {
	primary: '#101010',
	secondary: '#7f7f7f',
	background: '#efefef',
	border: '#303030',
}

const darkColors = {
	primary: '#efefef',
	secondary: '#7f7f7f',
	background: '#101010',
	border: '#b0b0b0',
}

const useTheme = () => {
	const [theme, setTheme] = useState('dark')

	const toggleTheme = () => {
		const nextTheme = theme === 'dark' ? 'light' : 'dark'
		setTheme(nextTheme)
	}

	const colors = theme === 'dark' ? darkColors : lightColors

	return { colors, currentTheme: theme, toggleTheme }
}

export default useTheme
```
<hr>

## Closing Comments 👋
In this article, we learned how to create a custom hook to maintain the theme throughout the app. We also saw the usage of custom hook in any component. 👨‍💻

Comment below which custom hook you want to learn next. 💬

If you find this article useful, share it with your friends and follow me for regular update of my articles. 🔗

Rushi Patel, Signing Off! 😊