0

Say you use the useState hook to set some state:

const [text, setText] = useState('');

If I set some variable to text and setText like:

let textCopy = text;
let setTextCopy = setText;

If I try and use setTextCopy('Some text'), would this actually update both text and textCopy?

If this does not work, what would be the best way to approach this?

I know this is probably not a great question I just wasn't sure how to word it. If you have any helpful links I would appreciate it.

Ken
  • 1,155
  • 2
  • 19
  • 36

1 Answers1

0

You are right and wrong.

  // this means textCopy will be same as text content
  const textCopy = text
  // this means setTextCopy is Identical as setText
  const setTextCopy = setText

when you call setText, it'll change text in next cycle, and then once it enters the render, textCopy will be in sync with same content.

But if you ask me if textCopy is Identical as text, the answer is no.

windmaomao
  • 7,120
  • 2
  • 32
  • 36
  • Thanks, why is textCopy not identical to text? – Ken May 18 '21 at 22:52
  • 1
    because it's string, when assigning a string, it'll always allocating to new memory. However if it's a function or object, it's not the case. Since the ref can be assigned. – windmaomao May 18 '21 at 23:45