best way to remove a word from an array in a react app

34 Views Asked by At

I'm working on a speed typing game using React and I have this function that removes the word from the array after it's either skipped or entered correctly. I think there's a better way to do it by creating a new array/without directly removing it from my words array but I'm a bit stuck on implementation. What would be the best approach to refactor the remove word function?

import wordsArray from "./components/wordsArray";

export default function App() {
  const getRandomWord = () => {
    return wordsArray[Math.floor(Math.random() * wordsArray.length)];
  };
  const [word, setWord] = useState(getRandomWord());
  const removeWord = () => {
    const removedWordIndex = wordsArray.indexOf(word);
    wordsArray.splice(removedWordIndex, 1);
    if (wordsArray.length === 0) {
      setGameOver(true);
    }
  };
}
1

There are 1 best solutions below

1
Wyck On

I think you should use state for the list of words.

import wordsArray from "./components/wordsArray";

export default function App() {
  const [word, setWord] = useState(getRandomWord());
  const [wordlist, setWordlist] = useState(wordsArray);
  const getRandomWord = () => {
    return wordlist[Math.floor(Math.random() * wordlist.length)];
  };
  const removeWord = () => {
    const updatedWordlist = wordlist.filter(w => w !== word);
    setWordlist(updatedWordlist);
    if (updatedWordlist.length === 0) {
      setGameOver(true);
    }
  };
}