Skip to content

Instantly share code, notes, and snippets.

@melcor76
Last active July 30, 2019 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melcor76/7c5c6235821db70ea780703f71a136e0 to your computer and use it in GitHub Desktop.
Save melcor76/7c5c6235821db70ea780703f71a136e0 to your computer and use it in GitHub Desktop.
Reactangular - React function component
import React, { useState, useRef, useEffect } from 'react';
import '@reactangular/elements';
const App = () => {
const [counter, setCounter] = useState(0);
const buttonRef = useRef(null);
useEffect(() => {
const handleEvent = () => setCounter(counter + 1);
const btnAddToCart = buttonRef.current;
btnAddToCart.addEventListener('addToCart', handleEvent);
return () => btnAddToCart.removeEventListener('addToCart', handleEvent);
}, []);
return (
<>
<shopping-cart counter={ counter } />
<add-to-cart-button type="React" ref={ buttonRef } />
</>
);
};
export default App;
@ThomasBurleson
Copy link

ThomasBurleson commented Jul 29, 2019

Would it not be better to run the Effect only 1x using any empty dependency array?

useEffect(() => {    
  const handleEvent = () => setCounter(counter + 1);
  const btnAddToCart = buttonRef.current;

  btnAddToCart.addEventListener('addToCart', handleEvent);
  return () => btnAddToCart.removeEventListener('addToCart', handleEvent);

}, []);

@melcor76
Copy link
Author

Thanks Thomas, that sounds like a good idea!
I think I had it like that at first and now I don't remember why I added the counter.
Running the effect every time the counter changes shouldn't be necessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment