Nowadays theming is an essential part of the most web application that allowing users to customize the appearance of an application according to their preferences. This is one the important functional implementation when it comes to frontend development.
In this blog post, we will dive into implementing the useTheme() custom hook in React, a commonly discussed topic in frontend interviews as well.
Implementation of useTheme() custom hook
Before jumping into the useTheme() implementation, its important to know how useState() and useEffect() hooks work in react.
Let's start by creating a new custom hook named useTheme() that will handle the theme functionality. We will use the useState hook to manage the theme state and the useEffect hook to apply the selected theme.
import React, { useState, useEffect } from 'react';
const useTheme = () => {
const [theme, setTheme] = useState('light');
useEffect(() => {
document.body.className = theme;
}, [theme]);
return [theme, setTheme];
};
export default useTheme;
Theme Selection using useTheme() custom hook
Now, let's create a component that uses the useTheme() custom hook to allow users to toggle between light and dark themes
import React from 'react';
import useTheme from './useTheme';
const ThemeSelector = () => {
const [theme, setTheme] = useTheme();
const toggleTheme = () => {
setTheme((prevTheme) => prevTheme === 'light' ? 'dark' : 'light');
};
return (
<div>
<button onClick={toggleTheme}>Toggle Theme</button>
<p>Current Theme: {theme}</p>
</div>
);
};
export default ThemeSelector;
Usage Explanation
To use the useTheme() custom hook in your application, follow these steps:
- Create a new React component (e.g., ThemeSelector) and import the
useTheme()custom hook. - Use the
useTheme()hook in the component to manage the theme state. - Implement the desired theme selection logic within the component.
- Render the component in your application to allow users to toggle between themes.
Final thoughts
In this blog, You have successfully go through the implemented and usage of the useTheme() custom hook in React to handle theme functionality.
By mastering custom hooks like useTheme(), you can enhance the user experience and streamline the development process.
Remember to practice implementing custom hooks and explore different use cases to deepen your understanding of React development. This will help in both react development and frontend interviews.
Keep learning, and happy coding :)
