The error “Cannot read properties of null reading useState usage” usually occurs when you are trying to access the properties of a null object. In the case of React and TypeScript, it can happen when you are trying to access the state of a component before it has been initialized. To fix this error, you need to make sure that you are initializing your state properly before trying to access it. Here are a few things you can check. Make sure you have properly initialized your state with the useState
hook. For example:
const [myState, setMyState] = useState(null);
Check that you are not trying to access the state before it has been set. You can use conditional rendering to make sure the component doesn’t render until the state has been initialized
if (!myState) {
return null;
}
If you are passing state as a prop to a child component, make sure you are passing a non-null value. You can use optional chaining to handle null values
// Parent component
<MyChildComponent myProp={myState?.myValue} />
// Child component
interface MyChildProps {
myProp?: string;
}
function MyChildComponent({ myProp }: MyChildProps) {
// Check that myProp is not null before using it
if (!myProp) {
return null;
}
// Render component using myProp
}
You should be able to fix the Cannot read properties of null reading useState error in your React TypeScript application
Solution to useState
You need to use and define the state / useState inside the main function.