I'm new to using React Hook refs. I followed several code examples, with all of them referencing useRef
but the code simply didn't work. Yet when I changed it to createRef
then it worked perfectly. I'm thus curious what the difference between the two functions is?
// Near the top of my component
let companyNameRef = React.createRef();
// A useEffect added simply to give focus to a particular input element the first time the component is loaded
useEffect(() => {
if (companyNameRef.current) {
companyNameRef.current.focus();
}
}, [companyNameRef]);
// Within the input element
<Form.Control name='companyName'
as='input'
onChange={e => handleChange(e)}
ref={companyNameRef}
/>
If I change createRef()
to useRef()
or useRef(null)
or useRef('')
the initial focus functionality stops working.
Might anyone know why?