use-exposed-state.ts 879 B

12345678910111213141516171819202122232425
  1. import { type Dispatch, type SetStateAction, useEffect, useState } from 'react'
  2. import { useIdeContext } from '../context/ide-context'
  3. /**
  4. * Creates a state variable that is exposed via window.overleaf.unstable.store,
  5. * which is used by Writefull (and only Writefull). Once Writefull is integrated
  6. * into our codebase, it should be able to hook directly into our React
  7. * contexts and we would then be able to remove this hook, replacing it with
  8. * useState.
  9. */
  10. export default function useExposedState<T = any>(
  11. initialState: T | (() => T),
  12. path: string
  13. ): [T, Dispatch<SetStateAction<T>>] {
  14. const [value, setValue] = useState<T>(initialState)
  15. const { unstableStore } = useIdeContext()
  16. // Update the unstable store whenever the value changes
  17. useEffect(() => {
  18. unstableStore.set(path, value)
  19. }, [unstableStore, path, value])
  20. return [value, setValue]
  21. }