How to track temperature changes over time
This example demonstrates how to track temperature changes over time using the usePrevious
hook.
tsx
import { useState } from "react";
import { usePrevious } from "./usePrevious";
export default function App() {
const [temperature, setTemperature] = useState(20);
const previousTemperature = usePrevious(temperature);
const simulateTemperatureChange = () => {
setInterval(() => {
const randomChange = Math.floor(Math.random() * 5) - 2;
setTemperature((prev) => prev + randomChange);
}, 1500);
};
return (
<>
<p>Current Temperature: {temperature}°C</p>
<p>Previous Temperature: {previousTemperature ?? "N/A"}°C</p>
{previousTemperature !== undefined && (
<p>
{temperature > previousTemperature
? "It’s getting warmer! 🌡️"
: temperature < previousTemperature
? "It’s getting colder! ❄️"
: "No change in temperature. 🤔"}
</p>
)}
<button onClick={simulateTemperatureChange}>
Simulate temperature change
</button>
</>
);
}
typescript
import { useRef } from "react";
export const usePrevious = <T>(value: T): T | undefined => {
const currentRef = useRef<T>(value);
const previousRef = useRef<T>(undefined);
if (currentRef.current !== value) {
previousRef.current = currentRef.current;
currentRef.current = value;
}
return previousRef.current;
};