How to compare oldValues and newValues on React Hooks useEffect?

Cover Image for How to compare oldValues and newValues on React Hooks useEffect?
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

How to Compare oldValues and newValues on React Hooks useEffect?

šŸ¤” Have you ever wondered if there's a way to compare oldValues and newValues in useEffect on React Hooks, just like in the good old componentDidUpdate days?

šŸ‘‰ Well, you're in luck! In this post, we'll explore an easy solution to this problem. We'll address the specific issue of comparing values in a useEffect hook and provide a compelling call-to-action for you to engage with.

The Problem

Let's set the stage: imagine you have three inputs in your UI - rate, sendAmount, and receiveAmount. You want to put these three inputs under the useEffect hook to track any changes. Here are the rules to follow:

  • If sendAmount changes, calculate receiveAmount = sendAmount * rate.

  • If receiveAmount changes, calculate sendAmount = receiveAmount / rate.

  • If rate changes and either sendAmount > 0 or receiveAmount > 0, calculate receiveAmount = sendAmount * rate or sendAmount = receiveAmount / rate, respectively.

šŸ˜« Dealing with all these conditions in a single useEffect hook seems challenging, right? But worry not, we've got you covered!

The Solution

To solve this problem, we'll introduce a custom hook called usePrevious. This hook will allow us to keep track of the previous values of the inputs and compare them against the current values.

Here's a link to a helpful CodeSandbox that demonstrates the final solution.

How to Use usePrevious

  1. Create a new file called usePrevious.js and add the following code:

import { useRef, useEffect } from 'react';

export default function usePrevious(value) {
  const ref = useRef();

  useEffect(() => {
    ref.current = value;
  });

  return ref.current;
}
  1. Import the usePrevious hook into your component:

import usePrevious from './usePrevious';
  1. Inside your component, define the necessary state variables:

const [rate, setRate] = useState(0);
const [sendAmount, setSendAmount] = useState(0);
const [receiveAmount, setReceiveAmount] = useState(0);
  1. Use the usePrevious hook to track the previous values of the state variables:

const prevRate = usePrevious(rate);
const prevSendAmount = usePrevious(sendAmount);
const prevReceiveAmount = usePrevious(receiveAmount);
  1. Finally, inside the useEffect hook, compare the previous and current values to determine the necessary calculations:

useEffect(() => {
  if (prevSendAmount !== sendAmount) {
    const newReceiveAmount = sendAmount * rate;
    setReceiveAmount(newReceiveAmount);
  } else if (prevReceiveAmount !== receiveAmount) {
    const newSendAmount = receiveAmount / rate;
    setSendAmount(newSendAmount);
  } else if (prevRate !== rate && (sendAmount > 0 || receiveAmount > 0)) {
    const newReceiveAmount = sendAmount * rate;
    const newSendAmount = receiveAmount / rate;
    setReceiveAmount(newReceiveAmount);
    setSendAmount(newSendAmount);
  }
}, [prevSendAmount, prevReceiveAmount, prevRate, sendAmount, receiveAmount, rate]);

šŸŒŸ And there you have it! With the help of the usePrevious hook, you can now easily compare the oldValues and newValues in your useEffect hook.

Conclusion

React Hooks make it easier than ever to manage state and side effects. However, comparing oldValues and newValues in a useEffect hook can be a bit tricky. By using the usePrevious hook, you can simplify this process and handle specific conditions effortlessly.

So, why not give it a try? Use the provided solution and see how it improves your code! And if you have any questions or doubts, feel free to leave a comment below. We'd love to help you out!

šŸš€ Happy coding!


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

šŸ”„ šŸ’» šŸ†’ Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! šŸš€ Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings šŸ’„āœ‚ļø Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide šŸš€ So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? šŸ¤” Well, my

Matheus Mello
Matheus Mello