Strive for a minimum required state in a React component
Andrey Smolko
Posted on August 27, 2022
Keep a component state as minimal as possible and avoid unnecessary state synchronization .
🚫 Before refactoring - b is a redundant state which should be sync:
export default function App() {
const [a, setA] = useState(1);
const [b, setB] = useState(1);
function updateA(x) {
setA(x);
};
function updateB() {
setB(1 + a);
};
useEffect(() => {
updateB()
},[a])
return (
<div>
<button onClick={() => updateA(a+1)}>Click</button>
<p>a: {a}</p>
<p>b: {b}</p>
</div>
)
};
✅ After refactoring - a is a minimum sufficient state and just derive b from it:
export default function App() {
const [a, setA] = useState(1);
function updateA(x) {
setA(x);
};
function updateB() {
return a+1
};
return (
<div>
<button onClick={() => updateA(a+1)}>Click</button>
<p>a: {a}</p>
<p>b: {updateB()}</p>
</div>
)
};
💖 💪 🙅 🚩
Andrey Smolko
Posted on August 27, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.