[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(),
);