useState is not defined


I got { ‘useState’ is not defined no-undef } error while compiling React. App was doing just fine until I moved a component into a separate file, here’s the code

import React from "react"

function Counter(){
    const [num, setNum] = useState(0)
            <button onClick={()=>{
                setNum((prevState)=> prevState + 1)
            <button onClick={()=>{
                setNum(prevState => prevState - 1)

export default Counter

Right, the useState function is a named export or a property of the React module. The easiest way to import it would be:

import React, { useState } from 'react'
1 Like

I think you could also get to it by referring to it as React.useState, but I prefer the former method.

1 Like

Thanks, Kevin, this was a really silly thing that I overlooked :sweat_smile:

I would be lying if I said that I never made the same mistake. Another common one is to import a named export as default or vice versa and you can’t figure out why it is undefined. These things happen.

1 Like

By the way, can you help me with another thing there? I’m stuck again at my project, now I don’t know how to interact between my two components. I have one that has input in it and I wanted to make it so when the button is clicked, the input value is being passed to its sibling component, but I’ve just realized that I have no idea how to do that

Yeah, that’s the tricky part of React.

Different ways to handle it.

  1. Most basically, store that state in a component that is an ancestor to both child components. Passing the data down is easy enough. To allow the other child to change its ancestor’s state, pass a callback function down to the children.

  2. Use context.

  3. Use a state management tool like Redux.

But on the most basic level, first you need to know how to do #1. This is such a common point of confusion that I created a pen to demonstrate the concept.