0

I am fairly new to react and I was just wondering that why do we use this.state in constructor function and only state without constructor function while initializing state.

lets say:

i have created a component with constructor, here i have to specify this.state to intialize state.

    class Test {

   constructor(){
    super();
    this.state = {
       name : ""
   }

     }

   }

and if i create a component without constructor , i can use only state to initialize state:

 class Test{
   state = {
      name : ""
   }
   }
3
  • Can you provide a snippet of what you're referring to in particular? Commented Sep 7, 2020 at 4:44
  • Yes a snippet will help Commented Sep 7, 2020 at 4:46
  • I have added the snippet into the original question now. Commented Sep 8, 2020 at 8:59

1 Answer 1

1

You can initialize state like the below or can use React Hooks

import React from 'react';

class YourComponent extends React.Component {
  state = {
    title: 'hello world',
  };

  render() {
    const { title } = this.state;
    return <h1>{title}</h1>;
  }
}

export default YourComponent;

with Hook, you can initialize a state like the below.

import React, { useState } from 'react';

const YourComponent = () => {
  const [title, setTitle] = useState('hello world');

  return <h1>{title}</h1>;
};

export default YourComponent;
Sign up to request clarification or add additional context in comments.

1 Comment

It's not that how to intialize state, I am asking why do we use this.state in constructor function where as only state without constructor function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.