Sobes.tech
Middle+

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:

  1. useCallback((el) => () => { log(el); }, []) — here, a function is created that returns another function with a closure on el. But there are no dependencies, so el will always be the first or undefined, which is incorrect.

  2. 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.

  3. In arr.map(el => <SomeComp key={} onClick={() => submit(el)} />) — here, a wrapper function is correctly created, but the key is empty, which will cause warnings. The key should be unique.

  4. useMemo(() => ({c: a + b}), [a,b]) — creates a memoized object to avoid creating a new object on every render if a and b haven't changed.

  5. Child = React.memo(() => {}) — memoizes the component so it doesn't re-render unnecessarily.

Summary:

  • submit should accept el and return a function, with correct dependencies.
  • In onClick, do not call the function immediately; pass a handler function.
  • Keys should be unique.
  • useMemo and React.memo help 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}) => { /* ... */ });