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'))
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>
</>
);
}
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>
</>
);
}
const refContainer = useRef(initialValue);
//useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).
//The returned object will persist for the full lifetime of the component.
useRef is an kind of alternative to useState hook , with useRef you can get an reference to an element and than use the DOM/JS properties to modify it .
You can even call useRef as an tool which is used to apply all the DOM properties as you were doing in Javascript before coming to React.
If you use useRef than this apparoch is called un-controlled components.
import { useRef } from 'react';
function LogButtonClicks() {
const countRef = useRef(0);
const handle = () => {
countRef.current++; console.log(`Clicked ${countRef.current} times`);
};
console.log('I rendered!');
return <button onClick={handle}>Click me</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 />);