简体   繁体   中英

How does react hook works? And how come the value tracked by useState does not reset on re-rendering?

I am new to React and trying to wrap my head about hooks especially when used within function component.

Here is an example where the useState hook is used:

import React, { useState } from "react";

const StateTutorial = () => {
  const [inputValue, setInputValue] = useState("Pedro");

  let onChange = (event) => {
    const newValue = event.target.value;
    setInputValue(newValue);
  };

  return (
    <div>
      <input placeholder="enter something..." onChange={onChange} />
      {inputValue}
    </div>
  );
};

export default StateTutorial;

This is taken from here

I understand how to use it. I understand that on each call of setInputValue the state is updated, and the view is re-rendered and we see the new value of inputValue .

I assume, re-rendering would involve calling the StateTutorial function again.

My question then is, if StateTutorial is called on re-rendering, how come the inputValue value is not reset to the initial value? How does functional components and react hooks work? How is it possible that the state useState is tracking is not reset to the initial value on re-rendering, because looking at the code this is what I would expect.

To keep it somewhat short:

You're probably familiar with the concept of the virtual DOM. If not, then imagine that react keeps a representation of the actual browser DOM, represented as JavaScript objects in memory. The virtual DOM is then used for several optimizations.

In the case of hooks, the hook's value gets attached to the virtual node for the component. Since the actual virtual node object for your component stays the same across re-rendering of your StateTutorial , the actual hook value is also kept.

Personally, I found that the Build your own React Tutorial is a great and very accessible way to get a better understanding of these concepts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM