Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does useState() run in an endless loop if the argument is an object or array?

I’m using the useState() hook in Deno Fresh, which is based on Preact. In an island I have:

import { useState } from "preact/hooks";

export default function(){
  const [state, setState] = useState('hi')
  const str = 'a'
  setState(str)
  console.log(state)
} 

This works fine. But if I use an object instead:

- const str = 'a'
- setState(str)
+ const obj = {a: 'a'} 
+ setState(obj)

Then it’s trapped in an endless loop. Why is that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This boils down to the question:

console.log("a" === "a");
console.log({ x : "a" }  === { x : "a"}); //Why is this false when above is true

Preact or React or JS uses object references to compare objects. Hence, two objects will never be equal.
React will not be able to optimize the rendering, even if the objects are technically equal and will keep on rerendering

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading