Creating refs inside a loop

All we need is an easy explanation of the problem, so here it is.

I am trying to create multiple refs based on the length of input array.

export default function test(props) {
    const numRefs = props.data.length;
    let [refs, setRefs] = useState([]);

    for (let i = 0; i < numrefs; i++) {
        let ref = useRef(null);
        setRefs(result => [...result, ref]);
    }


    return (
        <div>
            // Then I want to return numRefs number of divs each with a ref = one of ref from refs array
            <div ref = {}></div>
        </div>
    )
} 

React doesn’t allow you to have hooks inside a loop and I am getting the error ->

‘ React Hook “useRef” may be executed more than once. Possibly because it is called in a loop. React Hooks must be called in the exact same order in every component render’

Is it possible to achieve this?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Make use of callback approach to assigning refs within a loop. You do not need multiple instances of useRef. You can create one ref and store all refs to div within it

export default function test(props) {
    const numRefs = props.data.length;
    let [refs, setRefs] = useState([]);
    let divRef = useRef({});


    return (
        <div>
            {Array.from(new Array(20)).map((_, i) => <div ref = {ref => divRefs.current[i] = ref}></div>)}

        </div>
    )
} 

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply