Skip to content

Instantly share code, notes, and snippets.

@samuelint
Created February 2, 2024 14:34
Show Gist options
  • Save samuelint/0e15dcde1e288dc17f842265bb6d0edd to your computer and use it in GitHub Desktop.
Save samuelint/0e15dcde1e288dc17f842265bb6d0edd to your computer and use it in GitHub Desktop.
import { ActionCreatorWithPayload } from '@reduxjs/toolkit';
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
interface Props<
TValue,
TAction extends ActionCreatorWithPayload<TValue>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TSelector extends (state: any) => TValue
> {
initial: TValue
action: TAction
selector: TSelector
}
export default function useHydrate<
TValue,
TAction extends ActionCreatorWithPayload<TValue> = ActionCreatorWithPayload<TValue>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TSelector extends (state: any) => TValue = () => TValue
>({ initial, action, selector }: Props<TValue, TAction, TSelector>) {
const dispatch = useDispatch();
useEffect(() => {
dispatch((action(initial)));
// Call only once
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return useSelector(selector);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment