I am trying to get some React code to work. I need to work with react.development.js
and not React on the server side. I am trying to solve a different issue and I wanted to use useState
for that, but this fails.
The start of my page has:
<head>
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
and much of React works. But when I try to use useState
, e.g. in:
const ReminderSet = () => {
console.log( "Reminderset Rendering");
const [reminders, setReminders] = useState(defaultReminder);
I get an error in the console, e.g. in Firefox:
Uncaught ReferenceError: useState is not defined
2
Answers
Explanation
useState
isn’t a global, it’s A) a property of theReact
object, and B) a named export from thereact
module. I suggest switching to using modules, in which case you can doimport { useState } from "react";
. But if you don’t want to do that, you can useReact.useState
orconst { useState } = React;
and then useuseState
directly.Using modules:
Live copy (using Babel standalone, which is why the script tag has an unusual type; don’t use Babel standalone, use a bundler like Vite or Rollup or Webpack [or alternatively, don’t use JSX]):
Not using modules:
Live example:
The issue you’re encountering is likely because "useState" is a React hook, and React hooks are only available when you’re using React components. In your case, you’re directly using React functions without defining React components.
try this:
const [reminders, setReminders] = React.useState(defaultReminder);