I would like to be able to conditionally set a state based on previous state changes with React Hooks. But if the state remains the same the component shouldn't re-render.
When using class components, I was able to achieve this using:
this.setState(prevState => {
if(prevState.value !== true) {
return { value: true }
}
return null
})
The code above sets the state to true, only if it's not true. However, if it's already true, the component doesn't re-render. I would like to achieve the same effect with React Hooks.
I know that with React Hooks, I can use the prevState like this:
setValue(prevValue => {
// some code
return newValue
})
However, I don't know how to prevent re-render if the state remains the same. Is it possible for me to prevent render after using React Hooks prevState? Thank you for your concern.
Two ways:
Wrap your component by memo
import { useEffect, useState, memo } from "react";
const App = () => {
const [test, setTest] = useState(false);
useEffect(() => {
console.log("re-rendered");
});
const setTestToTrue = () => {
setTest((v) => {
if (v !== true) return true;
return v;
});
};
return (
<div className="App">
<button onClick={setTestToTrue}>Set test to true</button>
</div>
);
};
export default memo(App);