CodexBloom - Programming Q&A Platform

TypeScript: How to properly type a React component that uses hooks with varying return types?

πŸ‘€ Views: 808 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-09
typescript react hooks

Hey everyone, I'm running into an issue that's driving me crazy. I'm converting an old project and I'm not sure how to approach I'm learning this framework and Could someone explain I'm stuck on something that should probably be simple. I'm sure I'm missing something obvious here, but I'm working on a personal project and I'm working on a React component that utilizes hooks to fetch data from an API. However, I’m facing challenges with correctly typing the state and the return type of the custom hook. Here’s a simplified version of my code: ```typescript import React, { useState, useEffect } from 'react'; interface DataResponse { id: number; name: string; } function useFetchData(url: string): [DataResponse | null, boolean, string | null] { const [data, setData] = useState<DataResponse | null>(null); const [loading, setLoading] = useState<boolean>(true); const [error, setError] = useState<string | null>(null); useEffect(() => { const fetchData = async () => { try { const response = await fetch(url); if (!response.ok) { throw new Error('Network response was not ok'); } const result: DataResponse = await response.json(); setData(result); } catch (err) { setError(err.message); } finally { setLoading(false); } }; fetchData(); }, [url]); return [data, loading, error]; } const MyComponent: React.FC<{ apiUrl: string }> = ({ apiUrl }) => { const [data, loading, error] = useFetchData(apiUrl); if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error}</div>; return <div>{data ? data.name : 'No data'}</div>; }; ``` The issue arises when I try to use the `data` returned from the `useFetchData` hook. TypeScript complains about potential `null` values, specifically when I try to access `data.name`. The error message I get is `Object is possibly 'null'.` Even though I check if `data` is not `null` before accessing its properties, TypeScript seems not to infer that correctly. I’ve tried adding explicit type assertions and using non-null assertions, but they feel like a workaround rather than a proper solution. I believe this might be related to TypeScript's strict null checks. How can I improve the typing for this scenario to ensure TypeScript understands that `data` will not be `null` when I access its properties in the component? Any best practices to handle this scenario would be greatly appreciated! This is part of a larger web app I'm building. Any help would be greatly appreciated! This is part of a larger CLI tool I'm building. Any ideas what could be causing this? This is part of a larger CLI tool I'm building. Any help would be greatly appreciated! Could this be a known issue? This is my first time working with Typescript 3.9. What's the correct way to implement this? For context: I'm using Typescript on Linux. Has anyone else encountered this? Thanks for any help you can provide!