DEV Community

ludy.dev
ludy.dev

Posted on • Originally published at weightconvert.com

Building a zero-dependency, sub-100ms weight converter: Why client-side state is all you need

This keeps the conversions accurate to 4 decimal places without adding layout shifts or overhead.

Bi-directional Instant State Binding

Instead of having a single "Convert" button, the site calculates as you type. I mapped every input field (kilograms, pounds, stones, ounces, grams) to a single base unit value in grams.

Whenever any input changes, the script calculates the base value in grams and instantly updates all other fields dynamically:

const updateAllFields = (baseGrams, activeInput) => {
  Object.keys(units).forEach(unit => {
    if (unit !== activeInput) {
      inputs[unit].value = roundTo(baseGrams / units[unit].conversionFactor);
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

This unidirectional flow keeps the UI reactive and predictable with less than 60 lines of code.

What are your thoughts on handling dynamic unit conversions? Would you have gone the Vanilla JS route or used a lightweight framework like Alpine? Let me know in the comments!

Top comments (0)