DEV Community

loading...

React refactor code #2

sakethk
Computer jock, Programmer, Technology enthusiast and Math ❤️ er.
・1 min read

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

Discussion (0)