Skip to content Skip to sidebar Skip to footer

React Hooks Usestate Setvalue Still Rerender One More Time When Value Is Equal

I have sample code below: function App() { console.log('render'); const [val, setVal] = React.useState(0); return (

{val}

Solution 1:

This thread may help you : React: Re-Rendering on Setting State - Hooks vs. this.setState

Also, you can check the second paragraph over here which says:

Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go “deeper” into the tree. If you’re doing expensive calculations while rendering, you can optimize them with useMemo.

Solution 2:

React can’t guess the ouput of render() won’t change: it has to render() again and compare the results with the previous render().

Then the magic happens: if there are no differences, the DOM is not updated; if there are differences, it tries to only create/destroy elements as needed, because that’s the expensive part, not running render() — well it should not be.

Changing the state normally triggers a call to render() (not necessarily DOM modifications) — but if you want control over that behavior, define shouldComponentUpdate.


Note: That goes for non-hook components. However, I didn’t know the behavior of hooks was slightly different from that of a regular component: it seems that you’re right in expecting setState not to trigger a render when the value is unchanged — see Yash Joshi's answer.

Post a Comment for "React Hooks Usestate Setvalue Still Rerender One More Time When Value Is Equal"