Why must I pass a function to the setter function of 'useState' in React?

I’m handling file uploads using react-dropzone, which calls the following function with a list of files:

    const [files, setFiles] = useState([])

    const onDrop = useCallback(async acceptedFiles => {
        uploadFiles(acceptedFiles)
    }, [])

I then upload the files using fetch:

    const uploadFiles = async acceptedFiles => {
        acceptedFiles.forEach(async (file) => {
            setFiles(array => [...array, fileState])

            await fetch('/upload', {
                method: 'POST',
                body: data
            }).then(res => {
                // etc
            })
        })
    }

If I replace the setFiles call with just setFiles([...files, fileState]) (not in a function) it breaks, but why is this?

78 thoughts on “Why must I pass a function to the setter function of 'useState' in React?”

  1. I have been exploring for a little bit for any high quality articles or blog posts in this kind of space .
    Exploring in Yahoo I at last stumbled upon this website.
    Studying this information So i’m glad to convey that I have a very good uncanny feeling I
    found out exactly what I needed. I most for sure will make certain to
    don?t fail to remember this site and give it a glance regularly. http://www.deinformedvoters.org/hydroxychloroquine

    Reply
  2. What i don’t realize is in reality how you are no longer really a lot more smartly-appreciated than you may be right
    now. You are very intelligent. You realize therefore significantly in the case of this subject, made me individually
    imagine it from a lot of various angles. Its like men and women aren’t interested until it is one thing to do with
    Woman gaga! Your individual stuffs nice. All the time deal with it up! https://buszcentrum.com/nolvadex.htm

    Reply

Leave a Comment