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

227
Views
combine multiple useState of adding value into array into single function in react

This question is just related to reducing the code complexity. I have 8 arrays, in which I have to add items based on a button click. what I did is make 8 separate functions for all these tasks. is there any solution to combine all these functions into a single function that accepts an array as a parameter and does the rest of the job?

const [deleteArray,setDeleteArray]=useState([]);
const [newArray,setNewArray]=useState([]);
    const handleDeleteParking = (id) => {
        setDeleteArray((deleteArray) => [...deleteArray, id]);
}
   const handleNewParking = (id) => {
        setNewArray((newArray) => [...newArray, id]);
}

I have a total of 8 arrays with 8 separate functions to add items to the array, how can I achieve this task with a single function.

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

0

You can't just pass the array into the function, since the array and the setArray function are different. But you can of course pass in the setter function instead:

const addToArray = (id, setStateFn) => {
    setStateFn((arr) => [...arr, id]);
}

// usage: instead of handleDeleteParking(id)
addToArray(id, setDeleteArray);
about 4 years ago · Juan Pablo Isaza Report

0

You could have created an object that will store all your values.

Check the below code that may help you.

const [data, setData] = useState({
   deleteParking: [],
   newParking: [],
});

const handleChange = (key, id) => {
   setData(prev => {
        return {
            ...prev,
            [key]: [
                ...prev[key],
                id,
            ]
        }
    });
}

handleChange('deleteParking', 1);
handleChange('newParking', 1);
about 4 years ago · Juan Pablo Isaza Report

0

You can merge all of your state into one state and then you can create common function to update particular state and then along with array (updated array) you can pass the property name. Like this:

const [arrState,setArrayState]=useState({deleteArr:[]});
const commonUpdateFunction=(id, propertyName)=>{
    setArrayState (prev=> ({...prev,[propertyName]:[...prev.[propertyName],id]}))
}

On click

const handleClick=(someId)=>{
    commonUpdateFunction(someId,deleteArr)
}
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!