I am new to this community and react development and currently developing a app for learning react. I have found that my current implementation causes re renders in every state update. How to fix this issue?
import React, { useState } from "react";
const Counter = () => {
const [count, setCount] = useState(0);
const handleIncrement = () => {
setCount(count + 1);
};
const handleDecrement = () => {
setCount(count - 1);
};
const handleReset = () => {
setCount(0);
};
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={handleIncrement}>Increment</button>
<button onClick={handleDecrement}>Decrement</button>
<button onClick={handleReset}>Reset</button>
</div>
);
};
export default Counter;
Searched solution on web
2
Answers
The default behavior would be the one you just described. In most cases, when state updates, the component should re-render to see the update.
If you want to re-render a complex component only when the props change, you can use memo, like this:
In your case, your component should update when the state changes, because I assume you want to show the count in the h1 when it increases.
Normally react should render the component every time the state is updated, but you can decide when to render something using useMemo.