I'm wondering which of these two approaches is best for handling state when using custom hooks in react.
Having read this article on writing testable react hooks I've started having a custom hook associated with a component to act as a single entry point for the state and business logic.
However, it has made me wonder which approach is best for handling state. Should I keep lots of state values and pass the setState action to other custom hooks or should I return a value and let the more specific hook handle the more specific state? I've made a basic example to illustrate what I'm trying to articulate!
// useMyComponent.ts
// Approach 1
export default (): {
foo: string;
} => {
const [foo, setFoo] = useState < string | undefined>();
// State contained within this custom hook
const [authorisedInfo, setAuthorisedInfo] = useState<string | undefined>();
const [googleToken, setGoogleToken] = useState<string | undefined>();
useEffect(() => {
// setState passed down and set within a different custom hook
useSignInWithGoogle(setGoogleToken);
}, []);
useEffect(() => {
if (!googleToken) return;
usePerformAuthCall(setAuthorisedInfo);
}, [googleToken]);
useEffect(() => {
if (!authorisedInfo || !googleToken) return;
const { foo } = doSomethingHere(authorisedInfo, googleToken);
setFoo(foo);
}, [authorisedInfo, googleToken]);
return { foo };
};
// Approach 2
export default (): {
foo: string;
} => {
const [foo, setFoo] = useState < string | undefined>();
useEffect(() => {
// state value passed back from the custom hook
const { googleToken } = useSignInWithGoogle();
}, []);
useEffect(() => {
if (!googleToken) return;
const { authorisedInfo } = usePerformAuthCall(setAuthorisedInfo);
}, [googleToken]);
useEffect(() => {
if (!authorisedInfo || !googleToken) return;
const { foo } = doSomethingHere(authorisedInfo, googleToken);
setFoo(foo);
}, [authorisedInfo, googleToken]);
return { foo };
};
Thanks for the help!