0

Are there two different ways of using State in React?

  1. I just read a resource, and this is one method within a function

    const [searchTerm, setSearchTerm] = React.useState('');
    setSearchTerm('abc');
    
  2. Another uses this.state property

    this.state ..
    
    this.setState({
        searchTerm: 'abc' // enter values here
     });
    

When should I utilize these two methods? I am using React 16 with functions and inquiring about the difference.

3
  • 1
    One is for function components (the first) and the other is for class components (the second). The type of component you have will dictate which you should use. Docs on Function and Class Components Commented Jul 19, 2021 at 18:38
  • I am using functions @BrianThompson Commented Jul 19, 2021 at 18:39
  • hi @BrianThompson feel free to write in answer if you want, and I can send points, thanks Commented Jul 19, 2021 at 18:44

2 Answers 2

2

Using these States depends on your component.

If you use functional component, you can use

const [searchTerm, setSearchTerm] = React.useState('');
setSearchTerm('abc');

Or, If you use class component, You can use

this.state ..

this.setState({
    searchTerm: 'abc' // enter values here
 });
Sign up to request clarification or add additional context in comments.

Comments

0

First one is a react hook and used in functional components. If you are creating functional components then you have to use a hook to use state.

Second one is used in class components. If you are creating a class component then you use a state object and then update the state by using this.setState

Comments

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.