React refactor code #2
sakethk
Posted on July 26, 2021
Actual code :
const Counter = ({}) => {
const [counter, setCounter] = useState(0)
const reset = () => setCounter(0)
return (
<div>
<p>{counter}</p>
<button onClick={() => setCounter(counter + 1)}>+</button>
<button onClick={() => setCounter(counter - 1)}>-</button>
<button onClick={() => reset()}>Reset</button>
</div>
)
}
Refactor stage 1 :
instead of setCounter(counter + 1)
if we use increment()
it would be more readable.
const Counter = ({}) => {
const [counter, setCounter] = useState(0);
const reset = () => setCounter(0);
const increment = () => setCounter(counter + 1);
const decrement = () => setCounter(counter - 1);
return (
<div>
<p>{counter}</p>
<button onClick={() => increment()}>+</button>
<button onClick={() => decrement()}>-</button>
<button onClick={() => reset()}>Reset</button>
</div>
);
};
Refactor stage 2 :
No inline functions
const Counter = ({}) => {
const [counter, setCounter] = useState(0);
const reset = () => setCounter(0);
const increment = () => setCounter(counter + 1);
const decrement = () => setCounter(counter - 1);
return (
<div>
<p>{counter}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>Reset</button>
</div>
);
};
đ đȘ đ
đ©
sakethk
Posted on July 26, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Understanding Higher-Order Components and Higher-Order Functions in JavaScript
September 19, 2024