React refactor code #2

sakethkowtha

sakethk

Posted on July 26, 2021

React refactor code #2

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
};
Enter fullscreen mode Exit fullscreen mode

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>
  );
};
Enter fullscreen mode Exit fullscreen mode
💖 đŸ’Ș 🙅 đŸš©
sakethkowtha
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