How to play sound when hovering in React

Key takeaways:

  • The use-sound library simplifies audio playback in React. It allows developers to play sounds in response to user actions, such as hovering over elements, by associating sounds with events like onMouseEnter.

  • To use use-sound, install it via npm in your React project. Ensure your audio files are accessible in the correct paths for seamless integration.

  • By attaching the onMouseEnter event handler to an element, you can trigger sound playback during hover actions. For example, hovering over a button can play a sound using the play function from the useSound Hook.

  • Combining sound effects with visual feedback, such as color transitions on hover, enhances the user experience by offering both auditory and visual cues.

In React, we can implement sound effects on hover by using the use-sound library. This library simplifies the process of playing audio files in a React application, allowing for engaging audio feedback. By associating a specific sound with the onMouseEnter event, we can trigger the playback of the sound when an element is hovered over. This functionality enhances user interactions, providing valuable audio feedback and creating a more immersive experience within your interactive React applications.

If you want to explore more about React, check out “What is React? A tutorial on how to get started” blog on the Educative platform.

Steps to play sound on hover in React

Let’s implement the solution by setting up a React application and installing the required dependencies.

Step 1: Installing React dependencies

  • To get started, ensure we have a React application set up. If we don’t have one yet, we can create a new React application using the following command:

npx create-react-app soundReact

This command creates a new folder called soundReact and sets up a basic React project structure.

  • Next, navigate to the root directory of the React project using the terminal:

cd soundReact
  • Once we are in the project directory, install the use-sound package using npm:

npm i use-sound
Installing sound package in React

This command adds the use-sound library to our project, enabling us to easily manage audio playback.

Note: If you want to learn more about how to create a React application, then look into it: How to create a simple app using React 

Step 2: Playing sound on hover

Below is a simple demonstration of playing an audio file when hovering over a button in React. Start by importing the necessary packages and defining the HoverSoundButton component:

import React from 'react';
import useSound from 'use-sound';
import buttonHoverSound from './hover.mp3'; // Replace with the path to your sound file

const HoverSoundButton = () => {
  const soundUrl = buttonHoverSound;
  const [play] = useSound(soundUrl);

  return (
    <button
      onMouseEnter={play}
      style={{
        padding: '10px 20px',
        fontSize: '16px',
        background: '#007BFF',
        border: 'none',
        borderRadius: '5px',
        color: '#fff',
        fontWeight: 'bold',
        cursor: 'pointer',
        outline: 'none',
      }}
    >
      Hover over me!
    </button>
  );
};

export default HoverSoundButton;
Playing sound on hovering in React

Code explanation

In the above code:

  • Line 11: The onMouseEnter event handler is attached to the button. This means that when the mouse pointer enters the button’s area, it will trigger the play function.

The play function comes from the useSound hook (line 7), which is initialized with the sound file specified (hover.mp3). Make sure to replace hover.mp3 with the correct path to your audio file (line 3), and then you can use the HoverSoundButton component in your main application to display the button. When the button is hovered over, it will play the sound you specified.

Note: Most browsers restrict audio playback until there’s an initial user interaction, such as a click. This means use-sound may not play the hover sound until the button is clicked once. After this initial interaction, it should work as expected on subsequent hovers.

Advanced example: Button with hover sound and visual feedback

The use-sound library enables us to create a button with a sound effect that plays when hovered over. The following example illustrates how to achieve this effect, dynamically triggering the sound by simply hovering over the button. Additionally, this advanced example incorporates both sound and visual feedback, including a color change on hover.

import React, { useState } from 'react';
import useSound from 'use-sound';
import hoverSound from './hover.mp3';

const SoundEffect = () => {
  const soundUrl = hoverSound;
  const [isButtonHovered, setIsButtonHovered] = useState(false);

  const [play] = useSound(soundUrl, { volume: 0.8 });

  const handleHover = () => {
    if (!isButtonHovered) {
      play();
      setIsButtonHovered(true);
    }
  };

  const handleMouseLeave = () => {
    setIsButtonHovered(false);
  };

  // CSS styles for the button
  const buttonStyles = {
    padding: '15px',
    fontSize: '24px',
    background: 'transparent',
    border: '2px solid #007BFF',
    borderRadius: '5px',
    color: '#007BFF',
    fontWeight: 'bold',
    cursor: 'pointer',
    outline: 'none',
    transition: 'background-color 0.2s, color 0.2s', // Add transition for smooth color change
  };

  // Styles for the button when hovered
  const buttonHoverStyles = {
    background: '#007BFF',
    color: '#fff',
  };

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        height: '100vh',
      }}
    >
      <button
        onMouseEnter={handleHover}
        onMouseLeave={handleMouseLeave}
        style={{ ...buttonStyles, ...(isButtonHovered ? buttonHoverStyles : {}) }}
      >
        Hover over me!
      </button>
    </div>
  );
};

export default SoundEffect;
Playing sound in React application

Code explanation

In the above App.js file:

  • Lines 11–16: The handleHover function triggers sound playback when the button is hovered over, using the onMouseEnter event. It also sets the isButtonHovered state to true to prevent repeated playback while the button is hovered.

    • Line 13: The play function from the useSound hook is invoked, which plays the hover.mp3 sound. This creates a delightful sound effect as the button is hovered over.

Inline styles are applied to give the button a smooth color transition, which enhances the user experience visually alongside the audio feedback.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

1

Which React event handler is commonly used to trigger sound playback on hover?

A)

onClick

B)

onMouseLeave

C)

onMouseEnter

D)

onChange

Question 1 of 20 attempted

Conclusion

Adding sound effects when hovering over elements in React using the use-sound library can greatly enhance user interactions, providing valuable audio feedback. This approach is especially useful for creating interactive React applications.

For more resources on adding audio in React applications, check out the “How to play sound in React” Answer on implementing sound effects.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to play audio on hover?

To play audio on hover in a React application, you can use the use-sound library, which simplifies audio management. First, install the library using npm. Then, import the sound file and the useSound Hook into your component. Attach the onMouseEnter event to the element you want to trigger the sound. When the mouse hovers over the element, the sound will play automatically, enhancing user interaction with audio feedback.


How to play sound in ReactJS

Playing sound in ReactJS involves using libraries like use-sound or the built-in HTML audio capabilities. With use-sound, you import the audio file and call the useSound hook to initiate it. You can then tie sound playback to user events, such as clicks or hovers, by calling the provided play function. This approach allows you to create a more engaging user experience with audio feedback.


How do I add a song in React?

To add a song in React, you can either use an audio file directly or integrate a music service API. First, import the audio file into your React component, ensuring it’s in a supported format like MP3 or WAV. You can utilize the HTML <audio> element to manage playback or use a library like use-sound for easier control. You can then implement event handlers to play, pause, or stop the song based on user interactions.


How to play and pause audio in ReactJS

To play and pause audio in ReactJS, you can use the HTML <audio> element or a library like use-sound. With the <audio> element, you can control playback using JavaScript methods like play() and pause(), typically bound to button clicks or other events. If using use-sound, initialize the sound with the Hook, and you can call the play and pause functions to control playback, allowing users to interact with the audio seamlessly.


How do I set a fixed audio volume upon loading React.js page, using useSound?

To set a fixed audio volume upon loading a React.js page using the use-sound library, follow these steps:

  1. Install use-sound: Ensure you have the library installed in your React project.
    npm install use-sound
    
  2. Import the useSound Hook: Import the useSound Hook in the component where you want to play the audio.
    import useSound from 'use-sound';
    
  3. Load the audio file with a fixed volume: Pass the volume as a configuration option when initializing useSound. The volume parameter accepts a value between 0.0 (mute) and 1.0 (full volume).
    const [play] = useSound('path/to/your/audio.mp3', { volume: 0.5 });
    
  4. Trigger the sound on page load: Use the useEffect Hook to trigger the sound when the page loads.
    import React, { useEffect } from 'react';
    import useSound from 'use-sound';
    
    const App = () => {
        const [play] = useSound('path/to/your/audio.mp3', { volume: 0.5 });
    
        useEffect(() => {
            play();
        }, [play]);
    
        return <div>Welcome to the app!</div>;
    };
    
    export default App;
    

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved