Skip to content

Instantly share code, notes, and snippets.

@marcolink
Created August 4, 2022 07:29
Show Gist options
  • Save marcolink/c0fda9989cdb5c73b52c0839f1a632a9 to your computer and use it in GitHub Desktop.
Save marcolink/c0fda9989cdb5c73b52c0839f1a632a9 to your computer and use it in GitHub Desktop.
React hook for a reduced boolean value
import { useEffect, useState } from "react";
function reduce(record: Record<string, boolean>): boolean {
return Object.keys(record).reduce((previousValue, currentValue) => {
if (!record[currentValue]) {
return false;
}
return previousValue;
}, true);
}
export const useAllTrue = (record: Record<string, boolean>) => {
const [state, setState] = useState(() => reduce(record));
useEffect(() => {
setState(reduce(record));
}, [record]);
return state;
};
@marcolink
Copy link
Author

Usage:

const isTrue = useAllTrue({hello: true, world: false}) // false
const isTrue = useAllTrue({hello: true, world: true}) // true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment