const submit = useCallback((el) => () => { log(el); }, []); arr.map(el => <button onClick={submit(el)} />) arr.map(el => <SomeComp key={} onClick={() => submit(el)} />) const param = useMemo(() => ({c: a + b}), [a,b]) return <Child value={param} /> Child = React.memo(() => {})
sobes.tech AI
Answer from AI
This code has several points related to optimization and correct use of React hooks:
-
useCallback((el) => () => { log(el); }, [])— here, a function is created that returns another function with a closure onel. But there are no dependencies, soelwill always be the first or undefined, which is incorrect. -
In
arr.map(el => <button onClick={submit(el)} />)—submit(el)is called immediately during rendering, not on click. You need to pass a function, not the result of a call. -
In
arr.map(el => <SomeComp key={} onClick={() => submit(el)} />)— here, a wrapper function is correctly created, but thekeyis empty, which will cause warnings. The key should be unique. -
useMemo(() => ({c: a + b}), [a,b])— creates a memoized object to avoid creating a new object on every render ifaandbhaven't changed. -
Child = React.memo(() => {})— memoizes the component so it doesn't re-render unnecessarily.
Summary:
submitshould accepteland return a function, with correct dependencies.- In
onClick, do not call the function immediately; pass a handler function. - Keys should be unique.
useMemoandReact.memohelp optimize renders.
Example of correction:
const submit = useCallback((el) => () => { log(el); }, []);
arr.map(el => <button key={el.id} onClick={submit(el)} />)
// or
arr.map(el => <SomeComp key={el.id} onClick={() => submit(el)} />)
const param = useMemo(() => ({c: a + b}), [a,b]);
return <Child value={param} />;
const Child = React.memo(({value}) => { /* ... */ });