Home > Blockchain >  why useState() is not working in react js?
why useState() is not working in react js?

Time:07-06

when I declare a use State variable, my react app stops working.. if I uncomment the useState then the code works fine. I don't understand what is the problem?


import React from "react";
import { Helmet } from "react-helmet";
import { Link } from "react-router-dom";
import useState from "react";

import "./login.scss";

const Login = (props) => {
  const [credentials, setCredentials] = useState({
    user_name: '',
    password: '',
  })


  return (
    <div className="application">
     
    </div>
  );
}

export default Login;


CodePudding user response:

There could be a few things wrong here:

  1. Are you importing useState from react?

import React, { useState } from "react"

  1. Are you setting value using setText or setting a default state value? Your current example sets default state for text as ''

  2. Are you returning text in the render method? E.g.

return <p>{text}</p>

  1. Are you using React v16.8 or greater? If not hooks will not be available

CodePudding user response:

put curly braces around useState where you imported it like so..

import { useState } from "react";

other than that everything looks fine!

you can potentially delete the line with

import React from "react";

but it's not gonna change anything :)

CodePudding user response:

Instead of:

import useState from "react";

Write:

import { useState } from "react";

Why do I need to add {} to the import?

Answer: when you import something that was exported with the "default" keyword - you don't need {}, but when you import something that was exported NOT as default, you must add {} and say exactly what you want to import.

  • Related