I'm trying to create a simple useState React hook library using tsup bundler and the usage example using both NextJs App Router and Page Router. I have tried using the library inside the App Router and it is working fine, but when I tried to use it on Page Router, it returns the error of

TypeError: Cannot read properties of null (reading 'useState')

Repository link: https://github.com/elianrichard/simple-react-package

Steps to reproduce

git clone https://github.com/elianrichard/simple-react-package.git
cd simple-react-package
npm install
npm run build

App Router

npm --prefix ./example/nextjs-app-router install
npm --prefix ./example/nextjs-app-router run dev

Page Router

npm --prefix ./example/nextjs-page-router install
npm --prefix ./example/nextjs-page-router run dev

I have tried to delete the node_modules inside the library directory, but the error still exists. I'm really confused where I went wrong, you can see all of the config inside the repo. Thankyou!

1

There are 1 answers

1
Lucifer On
import React from "react";

export default function useNewState() {
  const [state, setState] = React.useState(0);

  return {
    state,
    setState,
  };
}

based on your code u have write the useState but not using just returing it which is not corrct you must do like that

  import React from "react";

export default function MyComponent() {
  // Call the useNewState hook to initialize state
  const { state, setState } = useNewState(0);

  // Event handler to update state
  const handleClick = () => {
    setState(prevState => prevState + 1); // Increment state by 1
  };

  return (
    <div>
      <p>Current State: {state}</p>
      <button onClick={handleClick}>Increment State</button>
    </div>
  );
}

setState this value to use to store the data state this data is used to get the sotored value