React Stillness Component

website·Indexed 29 days ago

https://react-stillness-component.vercel.app/

A React component designed to implement keep-alive effects within the React framework to improve work efficiency.

Tokens
332
Snippets
1
Records
1
Agent score
25%

What's inside React Stillness

  1. 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>
    );