1

I want to set the const [solution, setSolution] = useState(0); with the value of a input element by pressing a button

I get the same result using createRef or using the useRef hook

reading What's the difference between useRef and createRef?

gives quit different answers what exactly thees to do, is there a clear inside about thees to methods ?

function Interface() {

    const [solution, setSolution] = useState(0);
  
    const solutionInp = useRef();
    //                --createRef();
    
    const onButtonClick = () => {
    // `current` points to the mounted text input element
    setSolution( solutionInp.current.value)
      };


return (
 
<input
 type="text"
 // value={solution}
 
 ref={solutionInp}
 // onInput={(e) => setSolution(e.target.value)}
 />
 </section>
<button type="button" onClick={onButtonClick}>do</button>
)}


seeman
  • 105
  • 1
  • 13
  • The link you provided gives all the answers. Use useRef in functional components, so it isnt recreated on rerender. In a class component use createState in the constructor as that is only used once. – DownloadPizza May 20 '21 at 07:24
  • Have you check the docs? createRef is a part of Class component API and clearly you see `useRef` as part of hooks (function components) API. – Dennis Vash May 20 '21 at 07:28

1 Answers1

3

createRef is for class components, calling it in a context of function component will be treated as a normal function, hence will RE-INITIAL your reference on every render.

useRef is for function components, you lose your ref on unmount lifecycle.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118