3 ms·
> Hooks as more like a DSL for declaring externalities, That's exactly right in my opinion. Hooks are the place to declare stateful and effectful (aka impure)
by bern4444 5y ago
> Hooks as more like a DSL for declaring externalities,
That's exactly right in my opinion. Hooks are the place to declare stateful and effectful (aka impure) logic. Using a hook is an equivalent signal to using a Future, or an IO in other languages like Scala.
Often combinations of useState and useEffect are best written as a custom hook to reduce noise in the containing component. An easy example can be seen in something like
const [ name, setName, isValid ] = useValidatedState(state, validationFunction);
Seeing that you can easily imagine how it would be implemented:
const useValidatedState = <T>(initialState: T, validationFunction: (val: T) => boolean) => {
const [state, setState] = useState(initialState);
const [isValid, setIsValid] = useState(validationFunction(initialState);
useEffect(() => { setIsValid(validationFunction(state)) } [state]);
return [state, setState, isValid];
};
Almost always if there's a useState that has an associated useEffect, it should be turned into its own custom hook.