@utilityjs/use-sync-effect
v1.0.2
Published
A React hook that is similar to the `React.useEffect` hook, except it's synchronous and will be called on server as well.
Downloads
15
Maintainers
Readme
A React hook that is similar to the React.useEffect
hook, except it's synchronous and will be called on server as well.
npm i @utilityjs/use-sync-effect | yarn add @utilityjs/use-sync-effect
Usage
import * as React from "react";
import useSyncEffect from "@utilityjs/use-sync-effect";
const MyComponent = (props, ref) => {
const focusState = React.useRef(props.focused);
// When `props.disabled` changed run the effect synchronously (and also on the first render)
// Look at it as `React.useMemo` hook but instead of returning some value,
// It registers a synchronous effect with a cleanup function.
useSyncEffect(() => {
if (props.disabled && focusState.current) focusState.current = false;
return () => {
// cleanup function
}
}, [props.disabled]);
// ... the code that immediately benefits from the effect ...
return (
<div>...</div>
);
};
API
useSyncEffect(effectCallback, dependencyList?)
declare const useSyncEffect = (
effectCallback: React.EffectCallback,
dependencyList: React.DependencyList
) => void;
effectCallback
The effect function.
dependencyList
The list of the attributes that effect callback depends on.