title: How to set ref for SectionList in functional component in React Native?
body: <p>Basically I wanted to use the <a href="https://reactnative.dev/docs/sectionlist#scrolltolocation" rel="nofollow noreferrer">scrollToLocation</a> method of <a href="https://reactnative.dev/docs/sectionlist" rel="nofollow noreferrer">SectionList</a>, but I can't manage to set the <code>ref</code> inside a functional component.</p>
  <p><em>Note: for the examples below, compulsory properties of SectionList are elided to improve clarity.</em></p>
  <p>I've tried to use <code>useRef</code>, but this does not work, <code>ref</code> is still <code>null</code> after 3 seconds.</p>
  <pre><code>const MyComponent = () =&gt; {
    const ref = React.useRef()
    React.useEffect(() =&gt;
      setTimeout(() =&gt; ref.scrollToLocation({itemIndex: 0, sectionIndex: 0}, 3000)
    )
    return (
      &lt;SectionList ref={ref} /&gt;
    )
  }
  </code></pre>
  <p>I've also tried to put the ref inside state, but this also does not work, as it results in maximum update depth exceeded:</p>
  <pre><code>const MyComponent = () =&gt; {
    const [state, setState] = React.useState({ref: null})
    React.useEffect(() =&gt;
      setTimeout(() =&gt; ref.scrollToLocation({itemIndex: 0, sectionIndex: 0}, 3000)
    )
    return (
      &lt;SectionList ref={ref =&gt; setState(state =&gt; ({...state, ref}))} /&gt;
    )
  }
  </code></pre>
  <p>Then, I also tried to using a plain variable, but that does not work too, as <code>ref</code> is still <code>null</code> after 3 seconds.</p>
  <pre><code>const MyComponent = () =&gt; {
    let ref;
    React.useEffect(() =&gt;
      setTimeout(() =&gt; ref.scrollToLocation({itemIndex: 0, sectionIndex: 0}, 3000)
    )
    return (
      &lt;SectionList ref={r =&gt; ref = r} /&gt;
    )
  }
  </code></pre>
  <p>Therefore I'm wondering if there is a way to get the ref of a SectionList inside a functional component.</p>