Virat
Virat

Reputation: 17

React useCallback with onClick not working. Rerenders child component

TimeChild re-renders in below image even after using useCallback

enter image description here

Upvotes: 0

Views: 1940

Answers (3)

nolan
nolan

Reputation: 467

Firstly, you need to be aware, only in special situation, it makes sense to stop child component from re-rendering. If your case is not that special, that might not be a good idea.

Secondly, if you are sure you have to do it, use React.memo, the usage is pretty like componentShouldUpdate in class component

Upvotes: 1

Nicholas Tower
Nicholas Tower

Reputation: 85132

When Time sets state, then Time is going to rerender. Then, unless you do something to stop it, all of its children will rerender too. If you want to stop a child from rerendering, then the child component needs to use React.memo.

const TimeChild = React.memo(() => {
  // ...
});

If you do this, then when TimeChild would render, it will first do an === comparison between each of its old props and each of its new props. If they are all the same, TimeChild will skip rendering.

The only role that useCallback plays in this is if TimeChild receives a function as a prop. If it does, then you need to make sure it receives the same function each time, or React.Memo will never be able to skip rendering because its props keep changing. But in your example there are no props at all being passed to TimeChild, so useCallback is not necessary.

Upvotes: 2

Akhil
Akhil

Reputation: 435

You can use 'useCallback' in this way :


    import React, { useCallback, useState } from "react";
    
    const App = () => {
      const [count, setCount] = useState(0);
    
      const callBckValue = useCallback(() => {
        setCount((count) => count + 1);
      }, []);
    
      return (
        <div>
          <h2>{count}</h2>
          <button type="button" onClick={callBckValue}>
            Click Me
          </button>
        </div>
      );
    };
    
    export default App;

Upvotes: 1

Related Questions