Compare commits

..

1 Commits

Author SHA1 Message Date
laktionov-as ef33d16373 Сделали React.memo и React.useMemo 2026-05-21 21:33:02 +03:00
2 changed files with 48 additions and 57 deletions
+48 -55
View File
@@ -1,67 +1,60 @@
import React, { useState, useReducer, useRef, memo } from 'react' import { memo, useState, useMemo } from 'react'
function tasksReducer(state, action) { function memoize(fn) {
switch(action.type) { const cache = new Map();
case 'ADD_TASK': return function(...args) {
return [...state, action.payload] const key = JSON.stringify(args);
case 'TOGGLE_TASK': if (cache.has(key)) {
return state.map(task => task.id === action.payload ? {...task, complite: !task.complite} : task) return cache.get(key);
case 'REMOVE_TASK': }
return state.filter(task => task.id !== action.payload) const result = fn.apply(this, args);
default: cache.set(key,result);
return state return result;
} }
} }
const TaskList = memo(function TaskList({tasks, onToggle, onRemove}) { function fibonachi(n, memo={}) {
console.log("Rendred") if (n in memo) {console.log(n);return memo[n];}
if (n <= 1) return 1;
memo[n] = fibonachi(n-1, memo) + fibonachi(n - 2, memo);
return memo[n];
}
const MyComponent = ({ value }) => {
console.log('Rendring');
return <div>{value}</div>
}
const MemoizedComponent = memo(MyComponent);
const Child = memo(({ children }) => {
console.log('Child component rendred');
return <div>{children}</div>;
});
const Parent = () => {
const [count,setCount] = useState(0);
const [text, setText] = useState('');
const stableChild = useMemo(() => <span>Memo text</span>,[]);
return ( return (
<ul> <>
{tasks.map(({id, text, complite}) => ( <Child>
<li key={id} {stableChild}
style={{textDecoration: complite ? 'line-through' : 'none' }}> </Child>
<input type="checkbox" checked={complite} onChange={()=>onToggle(id)} /> <input type="text" onChange={(e) => setText(e.target.value)} value={text} />
{text} <button onClick={() => setCount(count + 1)}>Increment {count}</button>
<button onClick={()=> onRemove(id)} style={{marginLeft: 10}}> </>
Удалить
</button>
</li>
))}
</ul>
) )
}) }
function App() { function App() {
const [tasks, dispatch] = useReducer(tasksReducer,[])
const [input,setInput] = useState('')
const [error,setError] = useState('')
const inputRef = useRef(null)
const addTask = () => {
if (input.trim() === '') {
setError('Пустой текст задачи')
return
}
setError('')
dispatch({
type: 'ADD_TASK',
payload: {id: Date.now(), text: input.trim(), complite: false }
})
setInput('')
inputRef.current.focus()
}
return ( return (
<div style={{padding: 20}}> <>
<h1>Список дел</h1> <h1>Hello, React!</h1>
<input ref={inputRef} value={input} onChange={e => setInput(e.target.value)} /> <Parent />
<button onClick={addTask}>Добавить</button> </>
{error && <p style={{color: 'red'}}>{error}</p>}
<TaskList tasks={tasks}
onToggle={id => dispatch({type: 'TOGGLE_TASK', payload: id})}
onRemove={id => dispatch({type: 'REMOVE_TASK', payload: id})} />
</div>
) )
} }
-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>
) )