[React] Performance issue - 01 useState with slow function call

Say we have code below in the application:

const generateRandomColor = () => {
  let result = '';

  for (let index = 0; index < 6; index++) {
    const [element] = shuffle(hex);
    result += element;
  }

  block(150);

  return result;
};

export default generateRandomColor;

// Component
const [correctAnswer, setCorrectAnswer] = useState(generateRandomColor());

So everytime, component re-render the function generateRandomColor() will be triggered, and inside that function, it has block(150), which slow this function down.

Tip 1: Don't trigger function call

  const [correctAnswer, setCorrectAnswer] = useState(() =>
    generateRandomColor(),
  );

 

posted @ 2023-03-06 15:30  Zhentiw  阅读(16)  评论(0编辑  收藏  举报