Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing setState rerenders entire functional component

Tags:

reactjs

In a class component when the state or props was changed the render method will execute, but I don't know in a functional component when the same happens which part of the code is rerendered?

like image 586
S. Hesam Avatar asked Dec 14 '25 04:12

S. Hesam


1 Answers

If you have some expensive calculation inside your component that you want to skip, you can use the useMemo hook. It will do the calculation the first time, and then on subesequent times it will only recalculate if one of the dependencies change. For example:

import React, { useMemo } from 'react';

const Example = ({ people }) => {
  const [ageFilter, ageFilter] = useState(10);
  const filteredPeople = useMemo({
    return people.filter(person => person.age >= ageFilter);
  }, [people, ageFilter]);

  return (
    <div>
      {filteredList.map(person=> (
        // some components
      ))}
    </div>
  )
}
like image 81
Nicholas Tower Avatar answered Dec 15 '25 18:12

Nicholas Tower