F
F
frontendo2020-02-15 21:23:47
JavaScript
frontendo, 2020-02-15 21:23:47

How is the performance of components with react hooks?

Interested in the question of creating arrow functions on each render, it seems like it was a bad practice

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
IT Sinyak, 2020-02-15
@Sin9k

With performance in functions with hooks it is better than in classes, because react fiber (it's a virtual tree rendering tool) is much better at optimizing functions than class instances.
Regarding your specific code, every time you re-create a function inside onClick for any render, although this does not make sense to you. Therefore, it needs to be memoized using useCallback. The code looks like this

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);
  const onClick = useCallback(() => {
    setCount(count +1);
  }, []);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={onClick}>
        Click me
      </button>
    </div>
  );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question