reactjs

React 18 useId cannot be in key


The error: React Hook "useId" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function. So, question, where we can use useId()? I also got the same id for my mapped divs with the code:

// @ts-ignore
import React, {useRef, useState, useId} from 'react';

interface InputLocationProps {
    cleanAddress(): void
}

export const InputLocation: React.FC<InputLocationProps> = ({cleanAddress}) => {
    const id = useId()
    const ref = useRef<HTMLInputElement>(null);
    const [text, setText] = useState<string>('');
    const [textArray, setTextArray] = useState<string[]>(['more']);
    const changeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
        setText(event.target.value)
    }
    const putTextInArray = (puttingText: string) => {
        setTextArray(prevState => [ ...prevState, puttingText])
    }
    const keyPressHandler = (event: React.KeyboardEvent<HTMLInputElement>) => {

        if (event.key === 'Enter') {
            event.preventDefault();
            putTextInArray(text)
            console.log(ref.current!.value)
            ref.current!.value = '';
            setText('');
            cleanAddress();
        }
    }
    return (
        <form>
            <label htmlFor="count">{text}</label>
            <input ref={ref} onChange={changeHandler} onKeyPress={keyPressHandler} type="text" id="count"/>
            {textArray.map(textArrayItem => {
                return <div key={useId()}>{textArrayItem}</div>
            })}
        </form>
    );
};

Solution

  • According documentation:

    const Component = () => {
      // outside callback
      const id = useId();
    
      return array.map((item, index) => <div key={`${id}-${index}`}>some content</div>
    }
    

    Regarding react doc pitfall about useId:

    1. Use callback outside as mentioned in example - not inside (key={useId()}) and you don't have any side effects for simple list logic (readonly lists).
    2. For cases with editing data - it's best practice to use server response ids (key={item.id})