To remove a Firebase listener in React, use the off()
function.
jsximport React, { useEffect, useState } from 'react'; import firebase from './Firebase'; const Views = () => { const [views, setViews] = useState(0); useEffect( () => { // Defining path let ref = firebase.database().ref('views'); // Declaring listener let listener = ref.on('value', snapshot => { if(snapshot.val()){ setViews(snapshot.val()); } }); // Removing listener return () => ref.off('value', listener); }, []); return ( <div className = 'Views'> <div>Number of views: {views}</div> </div> ); } export default Views;
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.