import React, { useState, useRef, useEffect } from 'react'
import { render } from 'react-dom'
function App() {
const intervalRef = useRef()
const [count, setCount] = useState(0)
useEffect(() => {
intervalRef.current = setInterval(() => setCount(count => count + 1), 1000)
return () => {
clearInterval(intervalRef.current)
}
}, [])
return (
<>
<div style={{ fontSize: 120 }}>{count}</div>
<button
onClick={() => {
clearInterval(intervalRef.current)
}}
>
Stop
</button>
</>
)
}
render(<App />, document.querySelector('#app'))
import React, { useRef } from 'react';
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
//Use useRef to track application renders
import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";
function App() {
const [inputValue, setInputValue] = useState("");
const count = useRef(0);
useEffect(() => {
count.current = count.current + 1;
});
return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<h1>Render Count: {count.current}</h1>
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);