Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

write a react button that doesn't rerender on hover but has hover effects with tailwind…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514’s answer.
  1. User

    write a react button that doesn't rerender on hover but has hover effects with tailwind and global CSS variable colors

  2. Gemini Assistant

    You're asking for a perfect use case for pure CSS hover effects combined with Tailwind's arbitrary value syntax and global CSS variables.

    The key to "no rerender on hover" is to ensure that the hover effect is handled entirely by CSS and doesn't trigger any state updates in React. Tailwind's hover: utility classes do exactly this, and when combined with CSS variables, it's very powerful.

    Let's break it down.


    1. Global CSS Variables (src/index.css or src/App.css)

    First, define your global CSS variables. These are typically placed in your main CSS file that's imported globally (e.g., src/index.css if you're using Create React App or Vite with a similar setup).

    /* src/index.css */
    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
    :root {
      /* Primary Button Colors */
      --color-primary: #3498db; /* Blue */
      --color-primary-hover: #2980b9; /* Darker Blue */
      --color-text-on-primary: #ffffff; /* White text for primary */
    
      /* Secondary Button Colors */
      --color-secondary: #2ecc71; /* Green */
      --color-secondary-hover: #27ae60; /* Darker Green */
      --color-text-on-secondary: #ffffff; /* White text for secondary */
    
      /* Ghost/Outline Button Colors */
      --color-ghost-text: #34495e; /* Dark grey for ghost text */
      --color-ghost-border: #bdc3c7; /* Light grey for ghost border */
      --color-ghost-hover-bg: #ecf0f1; /* Lighter grey for ghost hover background */
    }
    
    /* Optional: You can also define global base styles here if needed */
    body {
      font-family: 'Inter', sans-serif; /* Example font */
    }
    

    2. React Button Component (src/components/MyButton.jsx)

    This component will use React.memo to prevent re-renders if its props haven't changed. Since the hover effect is purely CSS, the props (like onClick, children, variant) won't change when hovering, thus preventing the component from re-rendering.

    // src/components/MyButton.jsx
    import React from 'react';
    
    const MyButton = React.memo(({ children, onClick, variant = 'primary', className = '' }) => {
      // This console log will demonstrate that the component does NOT re-render on hover.
      // It will only re-render if its props (children, onClick, variant, className) change,
      // or if its parent re-renders AND its props are not memoized (e.g., onClick via useCallback).
      // With React.memo, it mostly depends on prop changes.
      console.log(`MyButton "${children}" rendered`);
    
      let baseClasses = "py-2 px-4 rounded-md font-semibold transition-all duration-300 ease-in-out cursor-pointer focus:outline-none focus:ring-2 focus:ring-opacity-75";
      let variantClasses = "";
      let hoverClasses = "";
      let focusRingColor = "";
    
      switch (variant) {
        case 'primary':
          variantClasses = "bg-[var(--color-primary)] text-[var(--color-text-on-primary)] border border-[var(--color-primary)]";
          hoverClasses = "hover:bg-[var(--color-primary-hover)] hover:border-[var(--color-primary-hover)]";
          focusRingColor = "focus:ring-[var(--color-primary)]";
          break;
        case 'secondary':
          variantClasses = "bg-[var(--color-secondary)] text-[var(--color-text-on-secondary)] border border-[var(--color-secondary)]";
          hoverClasses = "hover:bg-[var(--color-secondary-hover)] hover:border-[var(--color-secondary-hover)]";
          focusRingColor = "focus:ring-[var(--color-secondary)]";
          break;
        case 'ghost':
          variantClasses = "bg-transparent text-[var(--color-primary)] border border-[var(--color-primary)]";
          // On hover, ghost buttons typically fill with the primary hover color and change text to white
          hoverClasses = "hover:bg-[var(--color-primary-hover)] hover:text-[var(--color-text-on-primary)]";
          focusRingColor = "focus:ring-[var(--color-primary)]";
          break;
        case 'ghost-secondary':
          variantClasses = "bg-transparent text-[var(--color-secondary)] border border-[var(--color-secondary)]";
          // On hover, ghost buttons typically fill with the secondary hover color and change text to white
          hoverClasses = "hover:bg-[var(--color-secondary-hover)] hover:text-[var(--color-text-on-secondary)]";
          focusRingColor = "focus:ring-[var(--color-secondary)]";
          break;
        // Add more variants as needed
        default:
          console.warn(`Unknown button variant: ${variant}. Falling back to primary.`);
          variantClasses = "bg-[var(--color-primary)] text-[var(--color-text-on-primary)] border border-[var(--color-primary)]";
          hoverClasses = "hover:bg-[var(--color-primary-hover)] hover:border-[var(--color-primary-hover)]";
          focusRingColor = "focus:ring-[var(--color-primary)]";
      }
    
      return (
        <button
          type="button" // Good practice for accessibility and default browser behavior
          onClick={onClick}
          // Combine all classes. `className` prop allows consumer to add more classes.
          className={`${baseClasses} ${variantClasses} ${hoverClasses} ${focusRingColor} ${className}`}
        >
          {children}
        </button>
      );
    });
    
    export default MyButton;
    

    3. Usage Example (src/App.jsx)

    Here's how you'd use the button and verify it doesn't re-render on hover.

    // src/App.jsx
    import React, { useState, useCallback } from 'react';
    import MyButton from './components/MyButton'; // Adjust path as needed
    
    function App() {
      const [count, setCount] = useState(0);
    
      // Use useCallback to memoize the onClick functions for the buttons.
      // This is good practice with React.memo'd components to prevent unnecessary re-renders
      // if the parent component re-renders but the callback logic hasn't changed.
      const handlePrimaryClick = useCallback(() => {
        alert('Primary button clicked!');
        setCount(prev => prev + 1);
      }, []);
    
      const handleSecondaryClick = useCallback(() => {
        alert('Secondary button clicked!');
        setCount(prev => prev + 1);
      }, []);
    
      const handleGhostClick = useCallback(() => {
        alert('Ghost button clicked!');
        setCount(prev => prev + 1);
      }, []);
    
      return (
        <div className="min-h-screen bg-gray-100 flex flex-col items-center justify-center p-8">
          <h1 className="text-3xl font-bold mb-8 text-gray-800">React Button (No Re-render on Hover)</h1>
    
          <p className="mb-4 text-lg">
            Click count: <span className="font-bold text-blue-600">{count}</span>
          </p>
    
          <div className="flex space-x-4 mb-8">
            {/* Demonstrate a component that DOES re-render */}
            <div className="p-4 bg-gray-200 rounded-md">
              <p>This div re-renders when count changes: <span className="font-bold">{Math.random().toFixed(4)}</span></p>
              <button
                onClick={() => setCount(prev => prev + 1)}
                className="mt-2 py-2 px-4 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
              >
                Change Count (Forces App Re-render)
              </button>
            </div>
          </div>
    
          <div className="flex space-x-4">
            <MyButton onClick={handlePrimaryClick} variant="primary">
              Primary Button
            </MyButton>
    
            <MyButton onClick={handleSecondaryClick} variant="secondary">
              Secondary Button
            </MyButton>
    
            <MyButton onClick={handleGhostClick} variant="ghost">
              Ghost Button
            </MyButton>
    
            <MyButton onClick={handleGhostClick} variant="ghost-secondary">
              Ghost Secondary
            </MyButton>
          </div>
    
          <p className="mt-8 text-gray-600 text-sm">
            Check your browser's console. You'll only see "MyButton '...' rendered"
            when the app initially loads or when the `count` state changes (causing
            the parent `App` to re-render, and thus our `MyButton`s because their
            `onClick` props are recreated unless memoized with `useCallback` - which we've done here!).
            Hovering over the buttons *will not* trigger any new "rendered" messages.
          </p>
        </div>
      );
    }
    
    export default App;
    

    Setup Instructions:

    1. Create a React App:

      npx create-react-app my-button-app --template typescript # Or just without template for JS
      cd my-button-app
      

      or

      npm create vite@latest my-button-app -- --template react-ts # Or react for JS
      cd my-button-app
      npm install
      
    2. Install Tailwind CSS: Follow the official Tailwind CSS installation guide for your framework (e.g., React with Vite or Create React App): Tailwind CSS Docs - Framework Guides (or Vite)

      Example for Vite + React:

      npm install -D tailwindcss postcss autoprefixer
      npx tailwindcss init -p
      

      Modify tailwind.config.js:

      // tailwind.config.js
      /** @type {import('tailwindcss').Config} */
      export default {
        content: [
          "./index.html",
          "./src/**/*.{js,ts,jsx,tsx}",
        ],
        theme: {
          extend: {},
        },
        plugins: [],
      }
      

      Add Tailwind directives to your src/index.css:

      /* src/index.css */
      @tailwind base;
      @tailwind components;
      @tailwind utilities;
      /* Your custom CSS variables go here */
      :root {
        /* ... your CSS variables ... */
      }
      
    3. Place the files:

      • Create src/components/MyButton.jsx and paste the button component code.
      • Replace the content of src/App.jsx with the usage example code.
      • Add the CSS variables to your src/index.css (or equivalent global CSS file).
    4. Run the app:

      npm start # for Create React App
      npm run dev # for Vite
      

    Now, open your browser's developer console. When you hover over the buttons, you will not see any new "MyButton '...' rendered" messages, confirming that the component is not re-rendering on hover, thanks to CSS handling the visual effects.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.