Wednesday, 2 August 2023

Storing in memory and "freezing" React components in tabbing system

I'm trying to create a tabbing system. Here is the simplified version of the code:

import { useState, useEffect } from "react";

function Test({ id }) {
  const [text, setText] = useState("");

  return (
    <div>
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Type something..."
      />
      <h1>{text}</h1>
    </div>
  );
}

function App() {
  const [active, setActive] = useState(0);

  const [components, setCompoents] = useState([
    <Test key="1" id="1" />,
    <Test key="2" id="2" />,
    <Test key="3" id="3" />,
  ]);

  const handleActiiveChange = () => {
    setActive((active + 1) % components.length);
  };

  return (
    <div>
      <button onClick={handleActiiveChange}>Switch Tab</button>
      change: {active.toString()}
      <div>{components[active]}</div>
    </div>
  );
}

export default App;

In the final version, new tabs will be added dynamically to components. Although the current code sort of "works", the components (Test) do not preserve state as I would have hoped. The goal is that whenever a tab is rendered it keeps its previous state (e.g.: if I typed something in it, and then I cycle back to the tab I typed in it should not be lost.

What are common and best practices to "freeze", or store a react component in memory?

Ideally, the Test component (or whatever components will be put into this system) should not know anything about if they are active, or that they are in a tabbing system. They should just be regular components.

Thank you for reading!



from Storing in memory and "freezing" React components in tabbing system

No comments:

Post a Comment