News for hackers. Stuff that matters.
Re:Two custom React hooks by bern4444 on Friday December 17, 2021 @01:53PM (#29596607)
> 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.

There are no comments on this comment yet.