Event Listener
Native event & React
Example to demostrate why component lifecycle matters in a React component
Live Editor
function Example() { const [rCounter, setRCounter] = useState(0) let nCounterRef = useRef() useEffect(() => { const handleNativeClick = (e) => { nCounterRef.current.innerText = (parseInt(nCounterRef.current.innerText) + 1) } document.getElementById('btn-example-native').addEventListener('click', handleNativeClick); // return () => { // document.getElementById('btn-example-native').removeEventListener('click', handleNativeClick) // } }) const handleReactClick = () => { setRCounter(rCounter => rCounter + 1) } return ( <table><tbody> <tr><td> <button id="btn-example-native">Native Click</button> </td><td> <span ref={nCounterRef}>0</span> </td></tr> <tr><td> <button onClick={handleReactClick}>React Click</button> </td><td> <span>{rCounter}</span> </td></tr> </tbody></table> ); }
Result
Loading...