Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
react useContext setState is not a function

I'm working on a react app and I need to keep an array of names in my global state like on this file:

import React from "react";
import { useState } from "react";

const initialState = {
  nameList: [],
  test: 'hello'
}

export const Context = React.createContext()

const Data = ({ children }) => {
  const [state, setState] = useState(initialState)

  return(
    <Context.Provider value={[state, setState]}>
      {children}
    </Context.Provider>
  )
}

export default Data

However, when I try to set "nameList" to a new value in this other file:

const [state, setState] = useContext(Context);
const [currName, setCurrName] = useState('');

const handleAddName = () => {
  setState.nameList(prevState => [...prevState, currName])
}

I get a "setState.nameList is not a funtion" error and I can't find nor understand the reason why, any help would be much appreciated

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You're updating the state incorrectly, here's how to do it in your case:

const handleAddName = () => {
    setState(prevState => ({
        ...prevState,
        nameList: [...prevState.nameList, currName]
    }))
}

This will make sure that the state is updated immutably.

setState.nameList is wrong because setState is a function but not an object that will magically have the keys of your state.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!