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

230
Views
How to pass copy of object in React useState Initial State

What I am trying to achieve is after fitlerRequest function called filterListValue should manipulate.

But what happening is on radioHandleChange it's start manipulating the filterListValue.

I think they have the same memory reference but how to make a copy of it?

export default function CustomFilter(props) {
    const { filterListValue, setFilterListValue } = props;
const [radioValue, setRadioValue] = useState(filterListValue)

const radioHandleChange = (e, list) => {
        setRadioValue(radioValue => {
            let copy = [...radioValue]
            copy[indexChange].value = e.target.value
            copy[indexChange].id = list.id
            return copy
        });
}

const filterRequest = () => {
        setFilterListValue(radioValue)
        handleClose()
    };

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

0

Just make copies using .... Although not mentioned, looks like props.filterListValue is an array. So create a copy when starting with useState hook. Also, when setting radio value, make a copy of the item (since it is an object) so you are not mutating the state by mistake.

    const { filterListValue, setFilterListValue } = props;
const [radioValue, setRadioValue] = useState([...props.filterListValue])

const radioHandleChange = (e, list) => {
        setRadioValue(radioValue => {
            let copy = [...radioValue]
            let copyItem = {...copy[indexChange]}; 
            copyItem[indexChange].value = e.target.value
            copyItem[indexChange].id = list.id
            return copyItem
        });
}

PS:

You can destructure inside the function argument parenthesis. It is common practice:

export default function CustomFilter({filterListValue, setFilterListValue}) {
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!