JavaScript Array conflicting with React Component

I have three checkboxes that when selected fire a function. I’m using React-Bootstrap and my code is like this:

    let departmentArray = ([]);
    
      function handleCheck(val) {

        //DEPARTMENT ARRAY LOAD
        const index = departmentArray.indexOf(val);
        if (index > -1) {
          departmentArray.splice(index, 1);
        } else {
          departmentArray.push(val);
        }

        //REACT COMPONENT 
        if (val === "Maintenance") {
          setMaintCheck(!maintCheck);
        } else if (val === "Process") {
          setProcCheck(!procCheck);
        } else if (val === "Toolroom") {
          setToolCheck(!toolCheck);
        }

      }; 

  return (
    <>
       <Form.Check name={'department'} onClick={(e) => {handleCheck("Maintenance")}} checked={maintCheck} />
       <Form.Check name={'department'} onClick={(e) => {handleCheck("Process");}} checked={procCheck} />
       <Form.Check name={'department'} onClick={(e) => {handleCheck("Toolroom");}} checked={toolCheck} />
    </>
  )

The state of the checkboxes works with this code, but the array departmentArray does not work if the code underneath //REACT COMPONENT is present. If I remove these lines, the departmentArray loads correctly. I have no idea why the two would be affecting each other.

>Solution :

The departmentArray seems to be a normal var for React, when the code that is under // REACT COMPONENT executes the component rerenders and departmentArray reinitializes to []. You can put departmentArray out of the component as a constant or declare it as a state var for the component reacts to its changes

This is what I mean:

const departmentArray = []

const component = (props) => {

   const loadData = () => {
      // get data from somewhere
      departmentArray.push(...)
   }
   return <></>
}

Or you can declare departmentArray as a state var:

const [departmentArray, setDepartmentArray] = useState([])

const loadDepartments = () => {
   // load data
}

useEffect(loadDeparments, [])

Leave a Reply