Getting warning: Invalid hook call and Type error: cannot read properties of null (reading 'useContext') using Material UI component

Viewed 159

This is the component:

import React, { useEffect } from "react";
import { useStore } from "../zustand/store";
import shallow from "zustand/shallow";
import Grid from "@mui/material/Grid";

export const JoinChat = () => {
    const [userCount, setUserCount] = useStore(
        (state) => [state.userCount, state.setUserCount],
        shallow
    );
    const setChat = useStore((state) => state.setChat);
    const socket = useStore((state) => state.socket);

    useEffect(() => {
        socket.on("user_count", (data) => {
            console.log("user count run in join chat");
            setUserCount(data);
        });
    }, [socket, setUserCount]);

    const joinChat = async () => {
        if ("geolocation" in navigator) {
            await navigator.geolocation.getCurrentPosition(async (pos) => {
                const location = {
                    x: pos.coords.longitude,
                    y: pos.coords.latitude,
                };
                await socket.emit("create_chat", location);
                setChat(true);
            });
        } else {
            alert("You location is not available");
        }
    };

    return (
        <Grid>
            <div>
                {userCount ? <p>People online {userCount}</p> : null}
                <button onClick={joinChat}>Join chat</button>
            </div>
        </Grid>
    );
};

I get the following error in the console when I use grid to wrap the div: here

It renders fine without warning or error if I get rid of the material UI component

1 Answers

I met this same error when developing React18 + Vite (not a fun of cra)

I fixed this by clearing vite cache like so npx vite --force (I use pnpm, so my actual command is pnpx vite --force)

Here is how I created my react18 project: pnpm create vite my-react-app --template react-ts

Related