irychen / keepalive-for-react

React KeepAlive is a component that can cache the state of the component and reuse it when needed.
MIT License
187 stars 34 forks source link

Is it confict with the context built in the <Outlet /> #21

Closed ooPG233 closed 1 month ago

ooPG233 commented 1 month ago

I am using useOutlet() in the first layer with KeepAlive and using <Outlet context={{ value }} /> in the second layer, but this context seems never work

irychen commented 1 month ago
function DefaultOutlet() {
    const [count, setCount] = useState(0)
    return <div>
        <Outlet context={{ count, setCount }} />
        <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
}

export default DefaultOutlet
// in subpage render by Outlet
function Nested() {
    const { count, setCount } = useOutletContext<{ count: number; setCount: (count: number) => void }>();
    return <div>Nested {count} <button onClick={() => setCount(count + 1)}>Increment</button></div>
}

it work fine

attention! it cannot share state in another subpage (parallel) because DefaultOutlet is stored independently with keepalive, if you wanna share state, you can use a high level context to share state or use zustand etc