How to use the useState() hook with conditional operators with example

How to use the useState() hook with conditional operators with example

In React, the useState hook is used to add state to functional components. When combined with conditional operators, you can create components that dynamically render content based on the state.

Below is an example of how you might use the useState hook with conditional operators in a React functional component:

import React, { useState } from 'react';

const ExampleComponent = () => {
  // Using the useState hook to create a state variable and its corresponding updater function
  const [isVisible, setIsVisible] = useState(true);

  // Toggle the visibility state when a button is clicked
  const toggleVisibility = () => {
    setIsVisible(!isVisible);
  };

  return (
    <div>
      <h1>Conditional Rendering Example</h1>

      {/* Render content conditionally based on the state */}
      {isVisible ? (
        <p>This content is visible!</p>
      ) : (
        <p>This content is hidden!</p>
      )}

      {/* Button to toggle visibility */}
      <button onClick={toggleVisibility}>
        Toggle Visibility
      </button>
    </div>
  );
};

export default ExampleComponent;

In this example:

  • We use the useState hook to create a state variable named isVisible and its updater function setIsVisible. The initial state is set to true.

  • Inside the component's JSX, we use a conditional operator (? :) to render different content based on the value of isVisible. If isVisible is true, it renders one paragraph; otherwise, it renders another paragraph.

  • There's also a button with an onClick event handler (toggleVisibility) that toggles the value of isVisible when clicked.

Conclusion:

This is a simple example, but it demonstrates how to use useState to manage state in a functional component and conditionally render content based on the state. This pattern is frequently used in React applications to create dynamic and interactive user interfaces.