skip to Main Content

is it okay to do this in react, to put the event handlers and other functions that depend on useState outside the component? to avoid wrapping my functions in useCallback

like with this example:

import { useState } from "react";

const handleClick = (fn) => fn((prev) => prev + 1);

export default function App() {
  const [val, setVal] = useState(0);

  return (
    <>
      <p onClick={() => handleClick(setVal)}>clicked {val}</p>
    </>
  );
}

2

Answers


  1. The useCallback hook ensures that handleClick is memoized and won’t be recreated on every render unless its dependencies change.

    import React, { useState, useCallback } from "react";
    
    const App = () => {
      const [val, setVal] = useState(0);
    
      const handleClick = useCallback(() => {
        setVal((prev) => prev + 1);
      }, []);
    
      return (
        <>
          <p onClick={handleClick}>clicked {val}</p>
        </>
      );
    };
    
    export default App;
    
    Login or Signup to reply.
  2. Since React optimizes the re-render process by memoizing function references, you are implicitly using memoization. [wikipedia]

    it’s just an example, the event handler can be more than 1 line of code

    As long as the function stays pure and stateless, it will not be recreated upon each re-render.


    You can even export it from a separate module and then import the pure stateless functions you want to make use of.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search