-2

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?

2
  • 3
    Because strings are compared by value and objects by reference - that's a new object every time. Commented May 8, 2024 at 9:27
  • 3
    I suggest reading the caveats in the documentation. An unconditional state setter call in a component function is always a bad idea, whether with a string or something else, and it isn't always guaranteed React won't call the component function again as a result, even when you call it with the same value, though it usually won't. Commented May 8, 2024 at 9:33

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I guess I need to know how setState() works behind the scene. Do you have any good source that you recommend?
For Preact, this is the actual implementation, newArg !== oldArg. As simple of a check as it gets.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.