0

I am learning about the useCallback hook in React. There is an online demo accessible at https://codesandbox.io/s/red-sun-mw86q2?file=/src/App.js that I'm working with, and I've run into an issue - why is 'App is re-rendering' still being printed to the console when I click the button a second time? Can someone explain this for me this case, thanks!

1
  • 1
    Thanks for sharing example code. it will render when you put state at dependency of your useCallback fun. Commented Jul 27, 2023 at 4:25

1 Answer 1

0

re-render useCallback()

Hi, you should try to put your state data inside of dependency of usecallback function.

pls try like this, it will re-render.

const increment = useCallback(
    function () {
      setCount(count + 1);
    },
    [count]
  );

example

ref: docs. if you want a state or props to be reactive value, you should put that variable at dependency like useCallback(fun, [var1, var2])

useCallback(fn, dependencies) 
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your explanation. I understand the normal usage is what you described. However, in my example, when I click the button for the second time, the old and new value of count are both 1. So the component should not re-render in this case, right?
I see now what you mean. I saw a question same as your meaning.
Thanks! I've read that question and related answers. I also found another similar question here: https://stackoverflow.com/questions/57652176/react-hooks-usestate-setvalue-still-rerender-one-more-time-when-value-is-equal. After reading @sophiebits's comment(if what she said is correct🙂), I understand that this is because the updates are not processed until the render phase.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.