How do I prevent re-declaring a variable in a react component when it renders?

322 Views Asked by At

I have a React component called Flightlist, which receives an object from its parent component via props.newFlight.

I would like to push each object received from the parent to a local array, called flightList.

The problem I have is that I declare this array as an empty array at the beginning of my component, and every time that the component re-renders, the array that I pushed to, is re-declared as an empty array.

Hence, when I log the array to the console after the push() method, it always only contains the latest object received via props.

Please see my FlightList component below:

import Card from '../UI/Card';

const FlightList = (props) => {
  let flightList = [];

  flightList.push(props.newFlight);

  console.log('flightlist array', flightList);

  return (
    <>
      <ul>
        <li>
          <Card>
            <h1></h1>
          </Card>
        </li>
      </ul>
    </>
  );
};

export default FlightList;

(Note: The parent component is the one that manages the state, hence I am not managing state in the child component)

How can I declare this array in the child component without having it re-declared every time the state updates?

1

There are 1 best solutions below

0
Live bug help - www.dialect.so On

If the parent component is responsible for managing the state, then instead of passing an individual newFlight variable to FlightList, you should declare the flightList variable in the parent component using useState and then pass that as a prop to the FlightList component:

Parent component:

const [flightList, setFlightList] = useState([])

// When a new flight is added
const addNewFlight = (newFlight) => {
setFlightList([...flightList, newFlight])
}

return <FlightList flightList={flightList} />

Your FlightList component:

import Card from '../UI/Card';

const FlightList = (props) => {
  console.log(props.flightList)

  return (
    <>
      <ul>
        <li>
          <Card>
            <h1></h1>
          </Card>
        </li>
      </ul>
    </>
  );
};

export default FlightList;