I have an input element for a number that increments, I want to create my own increment buttons because I don't like the default buttons, they don't work well on mobile. So I created a button element that onClick handles the change in the number value and does other things with an onchange function that is fired from its parent, the main thing is that I need change a boolean state from false to true here, it worked fine when using the onChange from the input but when using the onClick from the button the parent component seems to re-render again thus losing the boolean state from false to true and then back to false again as its declared at the top.
Child component:
const PredictField = (props: any) => {
const { fixture, onchange, index, innerIndex } = props;
const [away, setAway] = useState(0);
const handleOnChangeAway = (matchId: string) => {
setAway((away) => away + 1);
onchange(matchId);
};
<input
className="score"
name={`awayTeam-${fixture.id}`}
type="number"
value={away}
onChange={(e) => handleOnChangeAway(e.target)}
min="0"
max="20"
/>
<button onClick={() => handleOnChangeAway(`awayTeam-${fixture.id}`)}>
<FontAwesomeIcon icon={faPlus} />
</button>
}
Parent component:
export default function Predict() {
const [showSave, setShowSave] = useState(false);
const onchange = (matchIdString: string) => {
setShowSave(true);
}
}
So basically the problem is that showSave
should change to true and it does but then it re-renders again to false ONLY with the button onClick, using the onChange in the input form it keeps being true, as I want it to.
How can I stop the Predict component re-rendering and thus changing the showSave back to false?
I've tried memo and useCallback and they didn't for me.