简体   繁体   中英

React (hooks) different value for refs on initial render

Can someone explain to me what is the reason for this situation!

Let's say I have a function which generates a random value on initial render. Then I assign the result using ref to keep the value unchanged after subsequent component updates. After that I assign the ref value to some state. The state is initialized with the ref value inside setTimeout.

import React, { useRef, useState } from "react";
import value from "./example";

function App(){

  const v = useRef(word());

  console.log(v.current); // Here for example the value is "test"

  setTimeout(() => {
    console.log(v.current); // Here the value is different
  }, 1000)

  const [state, setState] = useState(v.current);

  return (
    <div>{v.current}</div>
  )
}

I use setTimeout to illustrate the case but even without it the result is the same the state will be crated with different word although there is no component update.

How many times the component is render for the first initialization although there is no state change?

You are running your app in strict mode. Go to index.js and comment out the strict mode tag. You will find a single render.

This only applies to development mode. Lifecycles will not be double-invoked in production mode.

This is done by intentionally double-invoking the following functions:

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