0
const [movies, setMovies] = useState(getMovies());
function handleLike(movie) {
    const movieClone = [...movies];
    const index = movieClone.indexOf(movie);
    movieClone[index] = { ...movieClone[index] };
    movieClone[index].like = !movieClone[index].like;
    setMovies(movieClone);
  }

Hi, I'm new to React and I while I was taking an online tutorial the instructor makes a clone of an object from the movies array(movieClone[index] = { ...movieClone[index] };) and I just couldn't understand why? Because when I try to run the code without cloning the object from the array it works perfectly fine.

Thank you for your time.

Dalare
  • 21
  • 5
  • https://stackoverflow.com/questions/37755997/why-cant-i-directly-modify-a-components-state-really – Konrad Jan 01 '23 at 18:55
  • Does this answer your question? [How deep do I need to clone my state when only updating parts of the state?](https://stackoverflow.com/questions/44653269/how-deep-do-i-need-to-clone-my-state-when-only-updating-parts-of-the-state) – Konrad Jan 01 '23 at 18:57

1 Answers1

0

When using the useState hook, you should only modify the state variable by calling the setter function it gives you. That's how React knows it should queue re-renders for all the components using that variable. Mutating state directly circumvents this mechanism. Modifying movies without using setMovies might work in some cases, but it'll break the promises React makes to you about keeping everything updated.