I played around with react hooks, and I came across an issue that I do not understand.
The code is here https://codesandbox.io/embed/hnrch-hooks-issue-dfk0t The example has 2 simple components:
App Component
const App = () => {
const [num, setNum] = useState(0);
const [str, setStr] = useState();
const inc = () => {
setNum(num + 1);
setStr(num >= 5 ? ">= 5" : "< 5");
console.log(num);
};
const button = <button onClick={inc}>++</button>;
console.log("parent rerender", num);
return (
<div className="App">
<h1>App</h1>
<Child str={str}>{button}</Child>
</div>
);
};
Child Component
const Child = React.memo(
({ str, children }) => {
console.log("child rerender");
return (
<div>
<>
<h2>Functional Child</h2>
<p>{str}</p>
{children}
</>
</div>
);
}
(prev, props) => {
return prev.str === props.str;
}
);
So I have the child wrapped in a React.memo, and it should only rerender if str is different. But is also has children, and it get's passed a button which is incrementing a counter inside the parent (App).
The issue is: The counter will stop incrementing after it is set to 1. Can someone explain this issue to me and what I need to understand to avoid those bugs?