{"id":16507,"date":"2023-01-24T10:39:16","date_gmt":"2023-01-24T05:09:16","guid":{"rendered":"https:\/\/www.guvi.in\/blog\/?p=16507"},"modified":"2025-11-06T10:56:29","modified_gmt":"2025-11-06T05:26:29","slug":"how-to-toggle-an-element-in-react-react-hooks","status":"publish","type":"post","link":"https:\/\/www.guvi.in\/blog\/how-to-toggle-an-element-in-react-react-hooks\/","title":{"rendered":"How To Toggle an Element in React? | React Hooks"},"content":{"rendered":"\n<p>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\u2019s 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.<\/p>\n\n\n\n<p>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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Methods To Toggle an Element in React<\/strong><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Method 1: Using useState() hook<\/h3>\n\n\n\n<p>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:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 1: Create the initial state&nbsp;<\/strong><\/h4>\n\n\n\n<p>First, we&#8217;ll define the initial state. In this example, we have imported the useState from React and use a state variable called <strong>toggle<\/strong> which will determine whether the element is toggle or not.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useState } from \"react\";\n\nconst &#91;toggle, setToggle] = useState(true);<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 2: Create the toggle function&nbsp;<\/strong><\/h4>\n\n\n\n<p>Next, we&#8217;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.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useState } from \"react\";\n\nfunction App() {\n\n&nbsp;&nbsp;const &#91;toggle, setToggle] = useState(true);\n\n&nbsp;&nbsp;const onToggle = () =&gt; {\n&nbsp;&nbsp;&nbsp;&nbsp;setToggle(!toggle);\n&nbsp;&nbsp;};\n\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 3: Add the toggle button and element&nbsp;<\/strong><\/h4>\n\n\n\n<p>Now we can add the toggle button and the toggle element to our component. In this example, we&#8217;re using a simple ternary operator to determine whether the toggle element should be visible or not. When the visible state is <strong>true<\/strong>, the toggle element will be displayed, it will be hidden.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useState } from \"react\";\n\nfunction App() {\n\n&nbsp;&nbsp;const &#91;toggle, setToggle] = useState(true);\n\n&nbsp;&nbsp;const onToggle = () =&gt; {\n&nbsp;&nbsp;&nbsp;&nbsp;setToggle(!toggle);\n&nbsp;&nbsp;};\n\n&nbsp;&nbsp;return (\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;div className=\"container\"&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;div className=\"flex flex-col gap-4 items-center justify-center mt-10\"&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;button onClick={onToggle} className=\"p-2 bg-&#91;#8FD678] hover:bg-&#91;#559840] rounded-md text-white\"&gt;Toggle&lt;\/button&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{toggle &amp;&amp; &lt;h1 className=\"text-3xl font-bold\"&gt;Welcome to HCL Guvi&lt;\/h1&gt;}\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;\/div&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;\/div&gt;\n&nbsp;&nbsp;);\n}\n\nexport default App;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Method 2: Using useToggle() hook<\/h3>\n\n\n\n<p>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 &lt;h1&gt; element on a click of a toggle button.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Step 1: Create a useToggle() hook<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useCallback, useState } from \"react\";\n\nconst useToggle = (initialState = false) =&gt; {\n  \n  const &#91;state, setState] = useState(initialState); \/\/initialize the state\n  const toggle = useCallback(() =&gt; setState((state) =&gt; !state), &#91;]); \/\/toggle the state\n\n  return &#91;state, toggle];\n};<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Step 2: Create the initial state<\/h4>\n\n\n\n<p>Now we&#8217;ll use the custom useToggle() hook to initialize our state toggle.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function App() {\n   return (\n      const &#91;toggle, setToggle] = useToggle(); \/\/initialize the state using custom useToggle() hook\n      ...\n   );\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Step 3: Add the Toggle button and element<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useCallback, useState } from \"react\";\n\nconst useToggle = (initialState = false) =&gt; {\n  \n  const &#91;state, setState] = useState(initialState); \/\/initialize the state\n  const toggle = useCallback(() =&gt; setState((state) =&gt; !state), &#91;]); \/\/toggle the state\n\n  return &#91;state, toggle];\n};\n\nfunction App() {\n\n  const &#91;toggle, setToggle] = useToggle(); \/\/initialize the state\n\n  return (\n    &lt;div className=\"container\"&gt;\n      &lt;div className=\"flex flex-col gap-4 items-center justify-center mt-10\"&gt;\n        &lt;button\n          onClick={setToggle}\n          className=\"p-2 bg-&#91;#8FD678] hover:bg-&#91;#559840] rounded-md text-white\"\n        &gt;\n          Toggle\n        &lt;\/button&gt;\n        {toggle &amp;&amp; &lt;h1 className=\"text-3xl font-bold\"&gt;Welcome to HCL Guvi&lt;\/h1&gt;}\n      &lt;\/div&gt;\n    &lt;\/div&gt;\n  );\n}\n\nexport default App;\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Method 3: Using useReducer() hook<\/h3>\n\n\n\n<p>A useReducer() hook is a powerful tool for managing the state in <a href=\"https:\/\/www.guvi.in\/blog\/guide-for-react-component-libraries\/\" target=\"_blank\" rel=\"noreferrer noopener\">React components.<\/a> 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.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 1: Create the initial state&nbsp;<\/strong><\/h4>\n\n\n\n<p>First, we&#8217;ll import useReducer from React and then define the initial state. In this example, we&#8217;ll use an object with a single property called visible that will determine whether the toggle element is visible or not.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useReducer } from 'react';\n\nconst initialState = { visible: false };<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 2: Define the reducer function&nbsp;<\/strong><\/h4>\n\n\n\n<p>Next, we&#8217;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&#8217;ll define a single action type called TOGGLE that will toggle the visibility of the element.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const reducer = (state, action) =&gt; {\n&nbsp;&nbsp;switch (action.type) {\n&nbsp;&nbsp;&nbsp;&nbsp;case 'TOGGLE':\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return { ...state, visible: !state.visible };\n&nbsp;&nbsp;&nbsp;&nbsp;default:\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return state;\n&nbsp;&nbsp;}\n};<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 3: Use the useReducer hook&nbsp;<\/strong><\/h4>\n\n\n\n<p>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&#8217;ll use the dispatch function to dispatch the TOGGLE action whenever the toggle button is clicked.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useReducer } from 'react';\n\nconst initialState = { visible: false };\n\nconst reducer = (state, action) =&gt; {\n&nbsp;&nbsp;switch (action.type) {\n&nbsp;&nbsp;&nbsp;&nbsp;case 'TOGGLE':\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return { ...state, visible: !state.visible };\n&nbsp;&nbsp;&nbsp;&nbsp;default:\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return state;\n&nbsp;&nbsp;}\n};\n\nfunction App() {\n\n&nbsp;&nbsp;const &#91;state, dispatch] = useReducer(reducer, initialState);\n\n&nbsp;&nbsp;return (\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;div className=\"flex flex-col gap-4 items-center justify-center mt-10\"&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;button onClick={() =&gt; dispatch({ type: 'TOGGLE' })} className=\"p-2 bg-blue-700 hover:bg-blue-900 rounded-md text-white\"&gt;Toggle&lt;\/button&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{state.visible ? &lt;h1 className=\"text-3xl font-bold text-green-600\"&gt;Welcome to HCL Guvi&lt;\/h1&gt; : null}\n&nbsp;&nbsp;&nbsp;&nbsp;&lt;\/div&gt;\n&nbsp;&nbsp;);\n}\n\nexport default App;<\/code><\/pre>\n\n\n\n<p>Master React and beyond with our <a href=\"https:\/\/www.guvi.in\/zen-class\/full-stack-development-course\/?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=how-to-toggle-an-element-in-react-react-hooks\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Full Stack Development Course<\/strong><\/a>, 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How To Set Up a <strong>React App<\/strong>?<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 1: Install Node.js and npm<\/strong><\/h3>\n\n\n\n<p>Download and install <strong>Node.js<\/strong> from the official website https:\/\/nodejs.org. The Node.js installation also includes <strong>npm<\/strong>, which is the Node package manager.<br>Verify the installation in the terminal with:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>node -v\n\nnpm -v<\/code><\/pre>\n\n\n\n<p><strong>Step 2: Create a New React Application<\/strong><\/p>\n\n\n\n<p>Use <strong>create-react-app<\/strong>, a command-line tool that sets up the React environment automatically.<br>Run this command in the terminal:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npx create-react-app my-react-app<\/code><\/pre>\n\n\n\n<p>The <strong>npx<\/strong> command comes with npm version 5.2 or higher and runs packages without installing them globally. The tool creates a folder named <strong>my-react-app<\/strong> and installs all required dependencies.<\/p>\n\n\n\n<p><strong>Step 3: Navigate to the Project Directory<\/strong><\/p>\n\n\n\n<p>Move into the project folder by using:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>cd my-react-app<\/code><\/pre>\n\n\n\n<p><strong>Step 4: Start the Development Server<\/strong><\/p>\n\n\n\n<p>Run the local development server to preview the application:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm start<\/code><\/pre>\n\n\n\n<p>The application opens automatically in the browser at http:\/\/localhost:3000.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 5: Understand the Project Structure<\/strong><\/h3>\n\n\n\n<p>The project folder contains several key files and directories:<\/p>\n\n\n\n<ul>\n<li><strong>src\/<\/strong>: holds <a href=\"https:\/\/www.guvi.in\/blog\/best-reasons-to-learn-javascript\/\" target=\"_blank\" rel=\"noreferrer noopener\">JavaScript<\/a> files and React components<\/li>\n\n\n\n<li><strong>public\/<\/strong>: contains the <a href=\"https:\/\/www.guvi.in\/blog\/html-tutorial-guide-for-web-development\/\" target=\"_blank\" rel=\"noreferrer noopener\">HTML<\/a> template and static assets<\/li>\n\n\n\n<li><strong>package.json<\/strong>: lists project dependencies and scripts<\/li>\n<\/ul>\n\n\n\n<p>Each file serves a clear role in how React builds and renders the application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 6: Edit and Build<\/strong><\/h3>\n\n\n\n<p>Open the project in a code editor such as <strong>Visual Studio Code<\/strong>. Modify the files inside the <strong>src<\/strong> folder to create or update components.<br>After development, create a production build using:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm run build<\/code><\/pre>\n\n\n\n<p>The optimized build files are generated inside the <strong>build\/<\/strong> directory.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 7: Deploy the Application<\/strong><\/h3>\n\n\n\n<p>You can deploy the <strong>build<\/strong> folder to any web hosting service such as <a href=\"https:\/\/www.guvi.in\/blog\/how-to-use-github-repositories\/\" target=\"_blank\" rel=\"noreferrer noopener\">GitHub<\/a> Pages, Netlify, or Vercel.<br>Each platform provides clear instructions for deploying static web applications.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 8: Optional \u2013 Install Additional Libraries<\/strong><\/h3>\n\n\n\n<p>You can add libraries like <a href=\"https:\/\/www.guvi.in\/blog\/how-to-setup-react-router-v6-tutorial\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>React Router<\/strong><\/a> or <strong>Axios<\/strong> for routing and data fetching. Install them with commands such as:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm install react-router-dom\n\nnpm install axios<\/code><\/pre>\n\n\n\n<p>These tools improve functionality and maintain clean project organization.<\/p>\n\n\n\n<p><strong>Also, Read: <a href=\"https:\/\/www.guvi.in\/blog\/important-react-interview-questions\/\" target=\"_blank\" rel=\"noreferrer noopener\">Top React Interview Questions and Answers! [Updated]<\/a><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Common Use Cases of Toggling Elements in React<\/strong><\/h2>\n\n\n\n<p>Toggling elements in <a href=\"https:\/\/www.guvi.in\/blog\/what-is-reactjs\/\" target=\"_blank\" rel=\"noreferrer noopener\">React<\/a> 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.<\/p>\n\n\n\n<p><strong>Key Scenarios:<\/strong><\/p>\n\n\n\n<ul>\n<li><strong>Dropdown Menus:<\/strong> Toggle visibility of menu items when a user clicks the dropdown button. This helps manage navigation components efficiently.<\/li>\n\n\n\n<li><strong>Modal Popups:<\/strong> Show and hide modals for login forms, alerts, or confirmations using React hooks for precise state control.<\/li>\n\n\n\n<li><strong>Accordion Sections:<\/strong> Expand or collapse sections of content to improve readability and reduce clutter.<\/li>\n\n\n\n<li><strong>Theme Switching:<\/strong> Switch between dark and light themes by toggling state values that affect styling and component rendering.<\/li>\n\n\n\n<li><strong>Show or Hide Password Fields:<\/strong> Toggle visibility in password input fields to enhance user experience and security options.<\/li>\n<\/ul>\n\n\n\n<p>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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Best Practices for Toggling Elements in React<\/strong><\/h2>\n\n\n\n<p>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.<\/p>\n\n\n\n<p><strong>Recommended Practices:<\/strong><\/p>\n\n\n\n<ul>\n<li><strong>Use Descriptive State Names:<\/strong> Use names like isVisible or isOpen to make your state variables self-explanatory.<\/li>\n\n\n\n<li><strong>Keep Logic Simple:<\/strong> Avoid adding multiple responsibilities to a single toggle function. Each function should handle one state update.<\/li>\n\n\n\n<li><strong>Apply Conditional Rendering Wisely:<\/strong> Use ternary operators or short-circuit evaluation for visibility checks instead of deeply nested conditions.<\/li>\n\n\n\n<li><strong>Maintain Component Reusability:<\/strong> Extract toggle logic into custom hooks or separate utility functions so they can be reused across components.<\/li>\n\n\n\n<li><strong>Combine with CSS Transitions:<\/strong> Add smooth transitions with CSS to make toggling visually consistent and user-friendly.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">FAQs<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1761800917514\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>1. What is the best way to toggle an element in React?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>The simplest and most effective way to toggle an element in React is by using the <strong>useState() hook<\/strong>. It tracks the visibility of an element and updates it when triggered by a button or event. For larger applications, <strong>useReducer()<\/strong> or a <strong>custom useToggle()<\/strong> hook provides better control and scalability.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1761800940809\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>2. Why use React Hooks for toggling elements?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>React Hooks simplify state management inside functional components. Hooks like <strong>useState<\/strong>, <strong>useReducer<\/strong>, and <strong>useToggle<\/strong>remove the need for complex class components and make toggling logic reusable, clean, and easy to maintain.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1761800968309\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>3. Can I use conditional rendering with React Hooks to hide elements?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Yes, conditional rendering works perfectly with React Hooks. You can use a ternary operator or logical AND (&amp;&amp;) to decide whether an element should appear or stay hidden based on the current state value managed by a hook.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>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\u2019s 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 [&hellip;]<\/p>\n","protected":false},"author":60,"featured_media":16508,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[907],"tags":[],"views":"998","authorinfo":{"name":"Vaishali","url":"https:\/\/www.guvi.in\/blog\/author\/vaishali\/"},"thumbnailURL":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2023\/01\/How-to-Toggle-an-element-in-ReactJS-300x170.png","jetpack_featured_media_url":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2023\/01\/How-to-Toggle-an-element-in-ReactJS.png","_links":{"self":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/16507"}],"collection":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/users\/60"}],"replies":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/comments?post=16507"}],"version-history":[{"count":30,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/16507\/revisions"}],"predecessor-version":[{"id":92661,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/16507\/revisions\/92661"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media\/16508"}],"wp:attachment":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media?parent=16507"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/categories?post=16507"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/tags?post=16507"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}