How to use ReactJS's useMemo() to freeze the component's content?

622 Views Asked by At

The short question is: how do we freeze a component's content, probably by using useMemo() and telling it to freeze the content?

That's because useMemo(fn, []) takes the array to do a diff of values to decide whether to use the memoized value. It does not take a flag of true to tell it to use the memoized value.

I thought of one way, which is

useMemo(fn, [flag || `${Date.now()} ${Math.random()`])

so if flag is true, it won't evaluate the second part, and when it is true for a second time, the content is frozen. The second option is to use uuid() instead of the second part, which should be unique every time. The third choice is to gather all parameters that causes the output to be the same and put it into the array, which may be difficult to collect all, and is prone to bugs.

But this method is a bit hacky... and it may require comparing the performance of ${Date.now()} ${Math.random() vs uuid() because if it is CPU intensive, it only makes the situation worse.


Details:

This comes from wanting to slide a panel out and not update it, because the panel is very busy updating and the main window is busy updating continuously. To do that, when the user click the "Update Main Window" button, we dispatch an action to set the redux state, and we can slide out the panel, and on complete, we dispatch another action so that a redux state will tell the panel not to update and just return <div></div>. Another way is to just dispatch the first action, and be able to "freeze" the component. In this case, we don't need to dispatch the second action.

But useMemo() doesn't take a "freeze" flag, and take an array of dependencies instead. Is there a way to use a flag to cause it to freeze?

1

There are 1 best solutions below

1
On

If I understand correctly your actual dependency is on the "Update Main Window" button. You can add state like this and it should update content after user clicks on the button. useMemo documentation

const [updateFlag, setUpdateFlag] = useState(false);

useMemo(() => {}, [updateFlag]);

return (
  <div>
    <button onChange={() => setUpdateFlag(prevUpdateFlag => !prevUpdateFlag)}>update main window</button>);