简体   繁体   中英

React JS re-rendering

When a component re-renders as a result of calling the state setter function returned by useState, does the entire function component get called again or only parts of the function component get called?

function MyComponent() {
  let [count, setCount] = useState(0);
  
  const handleChange = () {
    setCount((prevCount) => prevCount+1)
  }

  return (
    <p onClick={handleChange}>
      Count = {count}
    </p>
  )
}

In the above example, when we click the paragraph element, handleChange() gets called which in turn calls the state setter function setCount() . This causes our component to re-render. But when the component re-renders( or the function MyComponent gets called), the useState(0) function gets called again. This should set the initial value of count to 0 again. So shouldn't the counter be stuck at 0 instead of progressing to 1, 2, 3 and so on?

Let say your component tree has parent and has children called childOne and childtwo. if you change the state of the ChildOne;Only the ChildOne get rendered, Not Parent and childtwo get rendered. But if you change the state of the parent, whole component tree get retendered

Whole functional component will be rerendered. If the props value which you are passing to the child component is not changing then you can prevent the rerendering of child component by using React.memo

This is the idea of hooks. They use closures .

If it was let count = 0 , then yes, if would reset to 0, this is why it is let [count] = useState(0)

The whole thing gets re-render and everything is getting re-calculated.

The argument you pass in useState / useRef is used only once, when the component mounts. If it is expensive operation, it recalculate on each render (there are ways to improve this), but the value of it is used only once. Then when you call setState it updates the value.

They work like this:

let ref = {};

const useRef = (defaultValue) => {
 if (!ref.current) {
    ref.current = defaultValue
 }
 return ref
}

The hook argument is used only once.

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