Skip to content
Advertisement

How do I update dynamic array inside useEffect in Typescript?

I have an array declared as

 var subjects : string[] = [];

Then set the array with the values as

subjects.push("C")
subjects.push("C++")

Then I want to update this array from useEffect. I tried below code

  useEffect(()=>{
    subjects.push("Java")
  },[])

when displaying subjects array, it is not updating with “Java”. Can anyone help me to solve this?

Advertisement

Answer

You are not triggering any re-rendering of your component. Re-renders run when props or states changes. You are trying to update an immutable piece of data in React world instead and the algorithm doesn’t know that it changed, the UI doesn’t reflect the updated subjects array as consequence.

So you could declare your subjects array in this way using the useState hook:

const [subjects, setSubjects] = useState<string[]>(["C++", "C"])

Then you can update it in this way:

setSubjects((prev) => [...prev, 'Java']);
Advertisement