0

I had thought once we call the trigger function then the page will re-render no matter what value we pass in but I found that if we pass a value same as the current value then it won't re-render.

But it's still weird when I tried this code below:

const Last = ()=>{
    const [fruit,eat] = useState('Apple')
    console.log('Current fruit is '+fruit)
    return(
        <div>
            <h1>{fruit}</h1>
            <button type='button' onClick={()=>eat('Banana')}>Try me</button>
        </div>
    )}

When the page first loaded, we passed 'Apple' into useState and hold by variable fruit, then we got 'Current fruit is Apple in the console'. Next I clicked the button and triggered the function 'eat' and passed 'Banana' into it, then we got page re-rendered and message 'Current fruit is Banana' in the console. Weirdly when I clicked the button again the function 'eat' got called and the page got re-rendered again. It shouldn't be as I pass a value 'Banana' same as current value hold by fruit. But when the third time I clicked the button, the page didn't re-render anymore. It's:

Page first load --> 'Current fruit is Apple' in console

first time click button --> 'Current fruit is Banana' in console

second time click button --> 'Current fruit is Banana' in console

third time click button --> No message in console

Now I am so confused with the mechanism of useState. Can someone tell me in which step I got wrong, really appreciate it.

I have read the React documentation about useState and the rule of hooks

Gap
  • 27
  • 4
  • 2
    also [React hooks call setState with same primitive value still cause re-render](https://stackoverflow.com/questions/65803394/react-hooks-call-setstate-with-same-primitive-value-still-cause-re-render) and from the docs [useState: Bailing out of a state update](https://reactjs.org/docs/hooks-reference.html#bailing-out-of-a-state-update) – pilchard Jan 15 '23 at 18:16

0 Answers0