How To Toggle an Element in React? | React Hooks
Nov 06, 2025 5 Min Read 319 Views
(Last Updated)
What happens when a user clicks a button and a hidden element suddenly appears? That small shift on the screen looks simple but relies on React’s efficient state control. Toggling an element is a core action that reflects how React updates the user interface based on state changes. Understanding this process helps you create smoother and more controlled user experiences.
Read the full blog to learn the complete steps for toggling an element using React Hooks and practical code examples that you can apply immediately.
Table of contents
- Methods To Toggle an Element in React
- Method 1: Using useState() hook
- Method 2: Using useToggle() hook
- Method 3: Using useReducer() hook
- How To Set Up a React App?
- Step 1: Install Node.js and npm
- Step 5: Understand the Project Structure
- Step 6: Edit and Build
- Step 7: Deploy the Application
- Step 8: Optional – Install Additional Libraries
- Common Use Cases of Toggling Elements in React
- Best Practices for Toggling Elements in React
- Conclusion
- FAQs
- What is the best way to toggle an element in React?
- Why use React Hooks for toggling elements?
- Can I use conditional rendering with React Hooks to hide elements?
Methods To Toggle an Element in React
Method 1: Using useState() hook
The useState() hook allows us to easily manage the state in our components. To toggle an element, we can create a state variable that keeps track of the visibility of the element, and a function that updates the state when the toggle button is clicked. See the example of how to do this:
Step 1: Create the initial state
First, we’ll define the initial state. In this example, we have imported the useState from React and use a state variable called toggle which will determine whether the element is toggle or not.
import React, { useState } from "react";
const [toggle, setToggle] = useState(true);
Step 2: Create the toggle function
Next, we’ll create a function that will toggle the visibility of the element. We have created a function that will be called when the toggle button is clicked, and it will update the visible state variable using the setToggle function.
import React, { useState } from "react";
function App() {
const [toggle, setToggle] = useState(true);
const onToggle = () => {
setToggle(!toggle);
};
}
Step 3: Add the toggle button and element
Now we can add the toggle button and the toggle element to our component. In this example, we’re using a simple ternary operator to determine whether the toggle element should be visible or not. When the visible state is true, the toggle element will be displayed, it will be hidden.
import React, { useState } from "react";
function App() {
const [toggle, setToggle] = useState(true);
const onToggle = () => {
setToggle(!toggle);
};
return (
<div className="container">
<div className="flex flex-col gap-4 items-center justify-center mt-10">
<button onClick={onToggle} className="p-2 bg-[#8FD678] hover:bg-[#559840] rounded-md text-white">Toggle</button>
{toggle && <h1 className="text-3xl font-bold">Welcome to HCL Guvi</h1>}
</div>
</div>
);
}
export default App;
Method 2: Using useToggle() hook
A useToggle() hook takes a parameter with the value true or false and toggles that value to the opposite. It is a custom hook created when we want to take some action to its opposite action. Here in the example, we will be showing and hiding an <h1> element on a click of a toggle button.
Step 1: Create a useToggle() hook
import React, { useCallback, useState } from "react";
const useToggle = (initialState = false) => {
const [state, setState] = useState(initialState); //initialize the state
const toggle = useCallback(() => setState((state) => !state), []); //toggle the state
return [state, toggle];
};
Step 2: Create the initial state
Now we’ll use the custom useToggle() hook to initialize our state toggle.
function App() {
return (
const [toggle, setToggle] = useToggle(); //initialize the state using custom useToggle() hook
...
);
}
Step 3: Add the Toggle button and element
import React, { useCallback, useState } from "react";
const useToggle = (initialState = false) => {
const [state, setState] = useState(initialState); //initialize the state
const toggle = useCallback(() => setState((state) => !state), []); //toggle the state
return [state, toggle];
};
function App() {
const [toggle, setToggle] = useToggle(); //initialize the state
return (
<div className="container">
<div className="flex flex-col gap-4 items-center justify-center mt-10">
<button
onClick={setToggle}
className="p-2 bg-[#8FD678] hover:bg-[#559840] rounded-md text-white"
>
Toggle
</button>
{toggle && <h1 className="text-3xl font-bold">Welcome to HCL Guvi</h1>}
</div>
</div>
);
}
export default App;
Method 3: Using useReducer() hook
A useReducer() hook is a powerful tool for managing the state in React components. It is more useful when we need to toggle the visibility of an element, as it allows us to handle the state changes in a clean and organized way.
Step 1: Create the initial state
First, we’ll import useReducer from React and then define the initial state. In this example, we’ll use an object with a single property called visible that will determine whether the toggle element is visible or not.
import React, { useReducer } from 'react';
const initialState = { visible: false };
Step 2: Define the reducer function
Next, we’ll define the reducer function that will handle the state changes. This function takes in the current state and an action, and returns the new state based on the action. In this example, we’ll define a single action type called TOGGLE that will toggle the visibility of the element.
const reducer = (state, action) => {
switch (action.type) {
case 'TOGGLE':
return { ...state, visible: !state.visible };
default:
return state;
}
};
Step 3: Use the useReducer hook
Now we can use the useReducer hook to manage the state in our Toggle component. The hook takes in the reducer function and the initial state and returns the current state and a dispatch function. We’ll use the dispatch function to dispatch the TOGGLE action whenever the toggle button is clicked.
import React, { useReducer } from 'react';
const initialState = { visible: false };
const reducer = (state, action) => {
switch (action.type) {
case 'TOGGLE':
return { ...state, visible: !state.visible };
default:
return state;
}
};
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div className="flex flex-col gap-4 items-center justify-center mt-10">
<button onClick={() => dispatch({ type: 'TOGGLE' })} className="p-2 bg-blue-700 hover:bg-blue-900 rounded-md text-white">Toggle</button>
{state.visible ? <h1 className="text-3xl font-bold text-green-600">Welcome to HCL Guvi</h1> : null}
</div>
);
}
export default App;
Master React and beyond with our Full Stack Development Course, build interactive web apps, learn front-end and back-end technologies, and create projects that showcase your coding skills. Get globally recognized certification and 100% placement support to launch your developer career.
How To Set Up a React App?
Step 1: Install Node.js and npm
Download and install Node.js from the official website https://nodejs.org. The Node.js installation also includes npm, which is the Node package manager.
Verify the installation in the terminal with:
node -v
npm -v
Step 2: Create a New React Application
Use create-react-app, a command-line tool that sets up the React environment automatically.
Run this command in the terminal:
npx create-react-app my-react-app
The npx command comes with npm version 5.2 or higher and runs packages without installing them globally. The tool creates a folder named my-react-app and installs all required dependencies.
Step 3: Navigate to the Project Directory
Move into the project folder by using:
cd my-react-app
Step 4: Start the Development Server
Run the local development server to preview the application:
npm start
The application opens automatically in the browser at http://localhost:3000.
Step 5: Understand the Project Structure
The project folder contains several key files and directories:
- src/: holds JavaScript files and React components
- public/: contains the HTML template and static assets
- package.json: lists project dependencies and scripts
Each file serves a clear role in how React builds and renders the application.
Step 6: Edit and Build
Open the project in a code editor such as Visual Studio Code. Modify the files inside the src folder to create or update components.
After development, create a production build using:
npm run build
The optimized build files are generated inside the build/ directory.
Step 7: Deploy the Application
You can deploy the build folder to any web hosting service such as GitHub Pages, Netlify, or Vercel.
Each platform provides clear instructions for deploying static web applications.
Step 8: Optional – Install Additional Libraries
You can add libraries like React Router or Axios for routing and data fetching. Install them with commands such as:
npm install react-router-dom
npm install axios
These tools improve functionality and maintain clean project organization.
Also, Read: Top React Interview Questions and Answers! [Updated]
Common Use Cases of Toggling Elements in React
Toggling elements in React is used in several real-world scenarios where the user interface needs to change dynamically based on interaction or data updates. Understanding these use cases helps developers design applications that respond smoothly to user actions and maintain clean state logic.
Key Scenarios:
- Dropdown Menus: Toggle visibility of menu items when a user clicks the dropdown button. This helps manage navigation components efficiently.
- Modal Popups: Show and hide modals for login forms, alerts, or confirmations using React hooks for precise state control.
- Accordion Sections: Expand or collapse sections of content to improve readability and reduce clutter.
- Theme Switching: Switch between dark and light themes by toggling state values that affect styling and component rendering.
- Show or Hide Password Fields: Toggle visibility in password input fields to enhance user experience and security options.
These examples show that toggling is more than a visual effect. It is a functional design pattern that manages how users interact with your React components effectively.
Best Practices for Toggling Elements in React
Clean and consistent state management is the foundation of efficient toggling in React. Following best practices keeps your code organized and easier to maintain as your project scales.
Recommended Practices:
- Use Descriptive State Names: Use names like isVisible or isOpen to make your state variables self-explanatory.
- Keep Logic Simple: Avoid adding multiple responsibilities to a single toggle function. Each function should handle one state update.
- Apply Conditional Rendering Wisely: Use ternary operators or short-circuit evaluation for visibility checks instead of deeply nested conditions.
- Maintain Component Reusability: Extract toggle logic into custom hooks or separate utility functions so they can be reused across components.
- Combine with CSS Transitions: Add smooth transitions with CSS to make toggling visually consistent and user-friendly.
Conclusion
Toggling an element in React with hooks builds a clear understanding of how React manages state updates and user interactions. The useState, useReducer, and custom useToggle hooks give developers flexible methods to control visibility and manage complex logic inside components. These hooks improve the structure of React applications and simplify state handling for clean, maintainable code. Knowing how to toggle elements also strengthens your ability to create interactive interfaces that respond quickly to user actions. Read the complete guide on how to toggle an element in React using hooks to master component state management efficiently and confidently.
FAQs
1. What is the best way to toggle an element in React?
The simplest and most effective way to toggle an element in React is by using the useState() hook. It tracks the visibility of an element and updates it when triggered by a button or event. For larger applications, useReducer() or a custom useToggle() hook provides better control and scalability.
2. Why use React Hooks for toggling elements?
React Hooks simplify state management inside functional components. Hooks like useState, useReducer, and useToggleremove the need for complex class components and make toggling logic reusable, clean, and easy to maintain.
3. Can I use conditional rendering with React Hooks to hide elements?
Yes, conditional rendering works perfectly with React Hooks. You can use a ternary operator or logical AND (&&) to decide whether an element should appear or stay hidden based on the current state value managed by a hook.



Did you enjoy this article?