user11526228
user11526228

Reputation: 21

React initialize state with or without constructor

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 : ""
   }
   }

Upvotes: 0

Views: 261

Answers (1)

phoenix
phoenix

Reputation: 36

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;

Upvotes: 1

Related Questions