Forcing an iframe to rerender with React

You may one day find yourself unlucky enough to work on a React application embedding an iframe. If that happens, chances are you might want to force it to refresh based on some change in the overlying component, that is to say have it rerender. But how would you do it?

An easy and not too shabby way is to abuse the key attribute, which serves as an identifier to tell a React component whether a given child element needs to be rerendered, and is typically used when building a list within a loop. How convenient! And even more so if you hide away all those shenanigans in a custom hook:

import { useState, useEffect } from "react";

export default function useChecksum(value) {
const [checksum, setChecksum] = useState(0);

useEffect(() => {
setChecksum(checksum => checksum + 1);
}, [value]);

return checksum;

The "checksum" here is but a dumb counter, which does a perfect job at yielding unique values over time - you can go with something more convoluted if you so desire. Anyhow, here is our in action:

import React from "react";
import useChecksum from "../hooks/useChecksum";

export default function FrameContainer({ someProp }) {
const checksum = useChecksum(someProp);

return (
<iframe key={checksum} src="..." title="I'm an outdated piece of technology!" />

The iframe will thus be refreshed when someProp changes. If you have any better way to deal with this, please let me know!