Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On React, how can I call a function on component mount on a functional/stateless component?

I have this functional/stateless component where I have a function filterByCardinalPoint which I need to call when component is mounted. Is there a way to do that without writing the component as a class?

const PassengersCircle = ({ navigationStore, passengersData }) => {
  const filterByCardinalPoint = () => {
    const passengersByCardinalPoint = filter('value');
    ...
  };

  return (...)
};
like image 541
Non Avatar asked Oct 14 '25 14:10

Non


1 Answers

You can use the useEffect hook to run a function when the component has been mounted. By giving it an empty array as second argument it will only be run after the initial render.

const PassengersCircle = ({ navigationStore, passengersData }) => {
  const filterByCardinalPoint = () => {
    const passengersByCardinalPoint = filter('value');
    // ...
  };

  useEffect(() => {
    filterByCardinalPoint();
  }, []);

  return <>{/* ... */}</>;
};
like image 174
Tholle Avatar answered Oct 17 '25 04:10

Tholle