Wednesday, December 14, 2022

[FIXED] Why does useState work with export default function but not class extends React.Component

Issue

Let's say I have a function called Login

Why does the following syntax work with the useState

export default function Login(){

    const [user, setUser] = useState({username: '', password: ''})

But when you use class Login extends React.Component, an error is given? Like this

class Sidebar extends React.Component {

  const [user, setUser] = useState({username: '', password: ''})

  render () {
      ....

Solution

You can read the React documentation here. React Hooks are a new paradigm and are intended to replace Classes and its logic, so this makes no sense to use hooks inside a class, that’s why it does not work.



Answered By - Rémi Mondenx
Answer Checked By - Timothy Miller (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.