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!
Asked
Active
Viewed 29 times
0

Shane
- 1
-
1Thanks for sharing example code. it will render when you put state at dependency of your useCallback fun. – Yewin Jul 27 '23 at 04:25
1 Answers
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]
);
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)

Yewin
- 160
- 1
- 7
-
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? – Shane Jul 27 '23 at 05:17
-
-
here the question, hope that help you. [https://stackoverflow.com/questions/76483739/react-updating-a-components-state-with-the-same-value-triggers-a-render](https://stackoverflow.com/questions/76483739/react-updating-a-components-state-with-the-same-value-triggers-a-render) – Yewin Jul 27 '23 at 05:37
-
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](https://stackoverflow.com/questions/57652176/react-hooks-usestate-setvalue-still-rerender-one-more-time-when-value-is-equal). After reading [@sophiebits's comment](https://github.com/facebook/react/issues/14810#issuecomment-462089702)(if what she said is correct), I understand that this is because the updates are not processed until the render phase. – Shane Jul 27 '23 at 07:21