[React2Hooks] Intelligent useEffect vs useLayoutEffect

JavaScript pattern

If a useEffect depends on layout etc. it should switch to useLayoutEffect.


Apply with the Grit CLI
grit apply intelligent_useEffect_to_useLayoutEffect

useEffect with conditions

BEFORE
useEffect(() => {
  // DOM Query Methods:
  // 1. getElementById
  const elementById = document.getElementById('myElementId');
  console.log('Element by ID:', elementById);

  // 2. getElementsByClassName
  const elementsByClass = document.getElementsByClassName('myClass');
  console.log('Elements by Class:', elementsByClass);

  // 3. querySelector
  const elementBySelector = document.querySelector('.mySelector');
  console.log('Element by Selector:', elementBySelector);
}, []);

useEffect(() => {
  ref.current = 'some value';
}, []);

useEffect(() => {
  console.log('useEffect');
}, []);
AFTER
useLayoutEffect(() => {
  // DOM Query Methods:
  // 1. getElementById
  const elementById = document.getElementById('myElementId');
  console.log('Element by ID:', elementById);

  // 2. getElementsByClassName
  const elementsByClass = document.getElementsByClassName('myClass');
  console.log('Elements by Class:', elementsByClass);

  // 3. querySelector
  const elementBySelector = document.querySelector('.mySelector');
  console.log('Element by Selector:', elementBySelector);
}, []);

useEffect(() => {
  ref.current = 'some value';
}, []);

useEffect(() => {
  console.log('useEffect');
}, []);

React.useEffect with conditions

BEFORE
React.useEffect(() => {
  const elementById = document.querySelector('myElementId');
  console.log('Element by ID:', elementById);
}, []);
AFTER
React.useLayoutEffect(() => {
  const elementById = document.querySelector('myElementId');
  console.log('Element by ID:', elementById);
}, []);

useEffect without conditions

BEFORE
useEffect(() => {
  const elementById = document.getElementById('myElementId');
  console.log('Element by ID:', elementById);
});
AFTER
useLayoutEffect(() => {
  const elementById = document.getElementById('myElementId');
  console.log('Element by ID:', elementById);
});

React.useEffect without conditions

BEFORE
React.useEffect(() => {
  const elementById = document.getElementsByClassName('myElementId');
  console.log('Element by ID:', elementById);
});
AFTER
React.useLayoutEffect(() => {
  const elementById = document.getElementsByClassName('myElementId');
  console.log('Element by ID:', elementById);
});