React Hooks: Why is .current null for useRef Hook?

后端 未结 3 583
温柔的废话
温柔的废话 2020-12-24 11:41

I have a simple example of a component:

function App() {
  const observed = useRef(null);
  console.log(observed.current);

  return (
    
3条回答
  •  没有蜡笔的小新
    2020-12-24 11:50

    At the time the console.log happens, the ref isn't yet set. Try putting your console.log into a useEffect hook and it works as you want it to.

    import React, { useRef, useEffect } from "react";
    import ReactDOM from "react-dom";
    
    import "./styles.css";
    
    function App() {
      const observed = useRef(null);
    
      useEffect(() => {
        console.log(observed.current);
      }, [observed]);
    
      return (
        

    Hello CodeSandbox

    Start editing to see some magic happen!

    ); } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);

提交回复
热议问题