Mastering React Hooks with a Simple Conversion Calculator

 

Mastering React Hooks with a Simple Conversion Calculator

Introduction

React hooks are powerful tools that allow you to use state and other React features in functional components. In this blog post, we'll explore three essential hooks: useState, useEffect, and useRef, by creating a simple conversion calculator that converts values between centimeters and inches. This use case provides a practical way to understand how these hooks work together to build interactive and dynamic applications.

Setting Up the Project

First, let's set up a basic React project and create a new component for our conversion calculator.

jsx
import { useEffect, useRef, useState } from 'react';
import './App.css';

function App() {
  const cmRef = useRef(null);
  const inchesRef = useRef(null);
  const [cm, setCm] = useState(0.0);
  const [inches, setInches] = useState(0.0);

  const cmChange = (event) => {
    setCm(event.target.value);
  };

  const inchesChange = (event) => {
    setInches(event.target.value);
  };

  useEffect(() => {
    if (document.activeElement === cmRef.current) {
      setInches(cm / 2.54);
    } else if (document.activeElement === inchesRef.current) {
      setCm(inches * 2.54);
    }
  }, [inches, cm]);

  return (
    <div>
      <label>
        CM: <input type="number" onChange={cmChange} step="0.01" value={cm} ref={cmRef} />
      </label>
      <br />
      <label>
        Inches: <input type="number" onChange={inchesChange} step="0.01" value={inches} ref={inchesRef} />
      </label>
    </div>
  );
}

export default App;

Understanding useState

The useState hook allows you to add state variables to your functional components. In our example, we use useState to manage the values of centimeters (cm) and inches (inches).

javascript
const [cm, setCm] = useState(0.0);
const [inches, setInches] = useState(0.0);
  • cm and inches hold the current values.

  • setCm and setInches are functions that update these values.

The state is updated whenever the user types into the input fields:

javascript
const cmChange = (event) => {
  setCm(event.target.value);
};

const inchesChange = (event) => {
  setInches(event.target.value);
};

Understanding useEffect

The useEffect hook allows you to perform side effects in your components, such as fetching data, directly manipulating the DOM, or in our case, synchronizing state values.

javascript
useEffect(() => {
  if (document.activeElement === cmRef.current) {
    setInches(cm / 2.54);
  } else if (document.activeElement === inchesRef.current) {
    setCm(inches * 2.54);
  }
}, [inches, cm]);
  • This effect runs every time cm or inches changes.

  • It checks which input field is active and updates the other field accordingly.

  • The empty dependency array [] ensures the effect runs only when cm or inches changes.

Understanding useRef

The useRef hook provides a way to reference DOM elements and persist values across renders without causing re-renders.

javascript
const cmRef = useRef(null);
const inchesRef = useRef(null);
  • cmRef and inchesRef are references to the centimeter and inch input fields.

  • These refs help us determine which input field is currently active, enabling us to update the other field correctly.

We attach these refs to the input elements using the ref attribute:

javascript
<input type="number" onChange={cmChange} step="0.01" value={cm} ref={cmRef} />
<input type="number" onChange={inchesChange} step="0.01" value={inches} ref={inchesRef} />

Conclusion

By combining useState, useEffect, and useRef, we created a simple yet effective conversion calculator. This example showcases how React hooks can work together to manage state, perform side effects, and interact with the DOM.

React hooks make your components more functional and maintainable. Try experimenting with these hooks in your projects and see how they can enhance your React applications.

Feel free to share your thoughts and feedback. Happy coding! 😊

Comments