Why is my hook variable in React not holding the state I set it to?

Viewed 56

I am using React and Redux. When my props.employees changes for the 1st time, useEffect runs and updates my teamsArr to the value of props.employees.

But my desire is to add the props.employees array to the teamsArr array that should already be filled with the previous props.employees array values.

But instead, whenever I change the value of props.employees, my teamsArr variable is initially empty and then changes the value to solely the current props.employees value.

I've been struggling to figure out how to solve this, so any help would be very welcome.

const Employees = (props) => {
    const [teamsArr, setTeamsArr] = useState([])


    useEffect(() => {
        const updatedTeamsArr = [...teamsArr, props.employees]
        setTeamsArr(updatedTeamsArr)
        }
    ,[props.employees])
1 Answers

You can take advantage of passing a function to setTeamsArr

useEffect(() => {
    setTeamsArr(prev => [...prev, ...props.employees])
    }
,[props.employees])

but in this case everytime prop.employees changes it'll be added but old values won't be removed.

Related