Compare commits

..

1 Commits

Author SHA1 Message Date
laktionov-as 7607146ff1 Разобрали useRef 2026-05-21 20:34:06 +03:00
4 changed files with 78 additions and 103 deletions
-27
View File
@@ -8,7 +8,6 @@
"name": "store-client", "name": "store-client",
"version": "0.0.0", "version": "0.0.0",
"dependencies": { "dependencies": {
"@tanstack/react-query": "^5.100.14",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0" "react-dom": "^19.1.0"
}, },
@@ -1305,32 +1304,6 @@
"win32" "win32"
] ]
}, },
"node_modules/@tanstack/query-core": {
"version": "5.100.14",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.100.14.tgz",
"integrity": "sha512-5X41dGpxgeaHISCRW2oYwcSycZeULZzAunaudXT9ov1KOTj9xwt0CH6hbwqP1/z74ZWF7rYFnDpyYH07XFcZew==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/react-query": {
"version": "5.100.14",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.100.14.tgz",
"integrity": "sha512-oOr6aRdSFEwWhzxEkD/9ZcItM3+LjBSkeVmadWKwUssAHTsqd/7bOjWrX4AbvEkoEhgAxzN0Xk6H/aYzXiYBAw==",
"license": "MIT",
"dependencies": {
"@tanstack/query-core": "5.100.14"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"react": "^18 || ^19"
}
},
"node_modules/@types/babel__core": { "node_modules/@types/babel__core": {
"version": "7.20.5", "version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
+1 -2
View File
@@ -4,13 +4,12 @@
"version": "0.0.0", "version": "0.0.0",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "vite build", "build": "vite build",
"lint": "eslint .", "lint": "eslint .",
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"@tanstack/react-query": "^5.100.14",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0" "react-dom": "^19.1.0"
}, },
+77 -72
View File
@@ -1,93 +1,98 @@
import React, {useState, useEffect, useRef } from 'react' import { useState, useRef, useEffect } from 'react'
//import { useQuery } from '@tanstack/react-query'
function useWindowWidth() { function Example() {
const [width,setWidth] = useState(window.innerWidth) const myRef = useRef(null);
const counterRef = useRef(0);
const [text, setText] = useState('');
useEffect(() => { useEffect(() => {
const handleResize = () => setWidth(window.innerWidth); myRef.current?.focus();
window.addEventListener('resize',handleResize); },[]);
return () => window.removeEventListener('resize',handleResize);
},[]) const handlerFocus = () => {
if(myRef.current) {
myRef.current.focus();
}
};
return width const handlerChange = (event) => {
setText(event.target.value);
}
counterRef.current += 1;
return <div>
<input ref={myRef} text="text" /><br />
Количество рендров: {counterRef.current}<br />
<input text="text" onChange={handlerChange} value={text} />
<button onClick={handlerFocus}>Поставить фокус на поле</button>
</div>
} }
function useLocalStorage(key, initValue) { function ClickCounter() {
const [value, setValue] = useState(()=>{ const countRef = useRef(0);
const stored = localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : initValue function handlerClick() {
}) countRef.current += 1;
//alert(`Нажали ${countRef.current} раз.`);
}
return <button onClick={handlerClick}>Нажать</button>;
}
function TimerComponent() {
const timerIdRef = useRef(null);
useEffect(() => { useEffect(() => {
localStorage.setItem(key, JSON.stringify(value)) timerIdRef.current = setTimeout(() => {
},[key, value]) alert("Прошло 3 секунды");
}, 3000);
return [value,setValue] return () => {
clearTimeout(timerIdRef.current);
}
},[]);
} }
/*
function useUserData(userId) { function PrevValue({ value }) {
return useQuery( const prevValueRef = useRef();
['user',userId],
() => fetch(`/api/user/${userId}`).then(res => res.json()), useEffect(() => {
{refetchOnWindowFocus: false} prevValueRef.current = value;
});
return (
<div>
Текущее значение: {value} <br />
Предыдущее значение: {prevValueRef.current}
</div>
) )
}*/ }
function useInput(initValue, validate) { function ScrollList() {
const [value, setValue] = useState(initValue); const listRef = useRef(null);
const [error, setError] = useState(null);
const onChange = e => { const scrollToBottom = () => {
const newValue = e.target.value if(listRef.current) {
setValue(newValue) listRef.current.scrollTop = listRef.current.scrollHeight;
if (validate) {
const validationResult = validate(newValue)
setError(validationResult)
} }
} }
return { value, error, onChange } return (
} <>
<div ref={listRef}
function useInterval(callback, delay) { style={{height: 200, overflowY: 'auto', border: '1px solid black'}}>
const savedCallback = useRef() {[...Array(20)].map((_,i)=>(
<div key={i}>Элемент {i + 1}</div>
useEffect(()=>{ ))}
savedCallback.current = callback </div>
},[callback]); <button onClick={scrollToBottom}>Прокрутить вниз</button>
</>
useEffect(()=>{
if (delay == null) return
const id = setInterval(()=>{
savedCallback.current()
},delay);
return () => clearInterval(id);
},[delay])
}
function App() {
const width = useWindowWidth();
const [theme, setTheme] = useLocalStorage('theme','light');
const username = useInput(
'',
value => value.length < 3 ? 'минимум 3 символа' : null
) )
}
function App() {
return ( return (
<> <>
<h1>Hello, React!{width}</h1> <h1>Hello, React!</h1>
<button onClick={()=>{ <ScrollList />
setTheme(theme === 'light' ? 'dark' : 'light')
}}>
Сменить тему
</button>
<p><input type="text"
value={username.value}
onChange={username.onChange} />
{ username.error ? username.error : '' }
</p>
</> </>
) )
} }
-2
View File
@@ -4,7 +4,5 @@ import { createRoot } from 'react-dom/client'
import App from './App.jsx' import App from './App.jsx'
createRoot(document.getElementById('root')).render( createRoot(document.getElementById('root')).render(
<StrictMode>
<App /> <App />
</StrictMode>
) )