I am trying to learn hooks and the useState method has made me confused. I am assigning an initial value to a state in the form of an array. The set method in useState is not working for me, both with and without the spread syntax.
I have made an API on another PC that I am calling and fetching the data which I want to set into the state.
Here is my code:
Neither setMovies(result) nor setMovies(…result) works.
I expect the result variable to be pushed into the movies array.
Much like .setState() in class components built by extending React.Component, the use of the updater, which is also asynchronous, will not immediately reflect the current closures; the main issue here is not only the fact that the state updates will reflect in the next re-render by which the existing closure is maintained, but the values within the hooks that are maintained are updated based on the function that is currently maintained; if you add the setTimeout, despite some timeout and not the updated one; console.loglog((result).\n\nThe use of the useEffect hook is the same as using componentDidUpdate in class components if you want to do an action on state update, as the setter returned by useState does not have a callback pattern useFfect(() => // operation on update of movies , [movies]); e.g.\n\nSetMovies(result) will replace the previous movies value in the state with those available from the async request as long as the syntax to update state is concerned, but if you want to merge the response with the previously existing values, you must use the callback syntax of state updation and the proper use of spread syntax like setMoves => ([…prevMailMailEs, ).