Implement keep-alive behavior using StillnessProvider and Offscreen
To achieve keep-alive effects in a React application (preserving component state when hidden), wrap the application in a
StillnessProvider and use the Offscreen component to toggle visibility. The Offscreen component controls whether the child component is rendered or kept in a 'still' state without being fully unmounted.import { StillnessProvider, Offscreen, useStillness } from 'react-stillness'; // Assuming library name based on context
import { useState } from 'react';
function App() {
const [show, setShow] = useState(true);
return (
<div>
<button onClick={() => setShow(show => !show)}>Toggle</button>
<Offscreen visible={show}>
<Count />
</Offscreen>
</div>
);
}
function Count() {
const [count, setCount] = useState(0);
const collected = useStillness({
mounted: (contract) => 'mounted',
unmounted: (contract) => 'unmounted',
collect: (contract) => ({
isStillness: contract.isStillness(),
stillnessId: contract.getStillnessId(),
}),
});
return (
<div className="count">
stillness: {collected.isStillness.toString()}
<p>class count: {count}</p>
<button onClick={() => setCount((count) => count + 1)}> Add </button>
</div>
);
}
render(
<StillnessProvider>
<App />
</StillnessProvider>
);