The best way to declare the State in ReactJs

Ishwar Deoolkar
5 min readSep 27, 2023
Photo by Rahul Mishra on Unsplash

Today’s everywhere is react, if you don’t react on time then time will react on you. Basically, I mean says Reactjs is very powerful frontend library and through this rapidly changing world. It’s gaining lots of attention through it.

Before I start saying something, you guys have heard about how to declare states in reactjs. And you might already have snatch your head about declaring a state in reactjs on Google or any YouTube channels and you have got plenty of answers to it. But still, I want to share my knowledge and experience about declaring state in reactjs.

Let’s, Get Started !!!

Initially, when Reactjs was introduced we were using class component to declare any stateful component, and functional component was used for presentation purpose.

For example 1: Declaring a single state into class components.

// Counter.jsx
import React, { Component } from 'react';

class Counter extends Component {
constructor(props){
super(props);
this.state = {
counter: 0,
};
};
handleIncrementCounter(){
this.setState(prevState => ({
counter: prevState.counter + 1
}));
};
handleDecrementCounter(){
this.setState(prevState => ({
counter: prevState.counter - 1
}));
};
render() {
return (
<div className="counter-container">
<p>Counter : {this.state.counter}</p>
<button className="btn" onClick={() => handleIncrementCounter()}>Increment Counter</button>
<button className="btn" onClick={() => handleDecrementCounter()}>Decrement Counter</button>
</div>
)
}
};

export default Counter;

For example 2: Declaring the multiple states into class components.

// ContactForm.jsx
import React, { Component } from 'react';

class ContactForm extends Component {
constructor(props){
super(props);
this.state = {
firstName: '',
lastName: '',
emailAddress: '',
phoneNumber: '',
message: '',
};
};
onChangeHandler(event){
const { name, value } = event.target;
this.setState(prevState => ({
[name]: value;
}));
};
render(){
return (
<div className="container-contact-form">
<h3>Contact Form</h3>
<form>
<div className="form-group">
<label htmlFor="firstName">Firstname</label>
<input
type="text"
id="firstName"
name="firstName"
placeholder="Enter the first name."
value={this.state.firstName}
onChange={(event) => this.onChangeHandler(event)}
/>
</div>
// Declare rest of fields here.
</form>
</div>
)
}
};

export default ContactForm;

As we know when React introduced the hooks, life became very easy. With hooks, you can declare the state in functional components as well. Today everyone is using functional components instead of class components and with the latest version of React class components have been deprecated.

So, let's jump into the functional component, How we can declare the state into a functional component, and which hooks we can use to declare a state.

Using the useState hook from React, We can declare the state into the functional component.

For example 1: Declaring the single states into function components using useState hooks from react.

// Counter.jsx
import React, { useState } from 'react';

const Counter = () => {
const [counter, setCounter] = useState(0);

const handleIncrementCounter = () => {
setCounter(prevState => ({ counter: prevState + 1 }));
};

const handleDecrementCounter = () => {
setCounter(prevState => ({ counter: prevState - 1 }));
};

return (
<div className="counter-container">
<p>Counter : {counter}</p>
<button className="btn" onClick={() => handleIncrementCounter()}>Increment Counter</button>
<button className="btn" onClick={() => handleDecrementCounter()}>Decrement Counter</button>
</div>
)
};

export default Counter;

For example 2: Declaring the multiple states into function components using useState hooks from react.

// Home.jsx
import React, { useState } from 'react';

const Home = () => {
const [counter, setCounter] = useState(0);
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [emailAddress, setEmailAddress] = useState('');
const [phoneNumber, setPhoneNumber] = useState('');

const handleIncrementCounter = () => {
setCounter(prevState => ({ counter: prevState + 1 }));
};

const handleDecrementCounter = () => {
setCounter(prevState => ({ counter: prevState - 1 }));
};

return (
<div className="home-container">
<div className="counter-container">
<p>Counter : {counter}</p>
<button className="btn" onClick={() => handleIncrementCounter()}>Increment Counter</button>
<button className="btn" onClick={() => handleDecrementCounter()}>Decrement Counter</button>
</div>
<div className="container-contact-form">
<h3>Contact Form</h3>
<form>
<div className="form-group">
<label htmlFor="firstName">Firstname</label>
<input
type="text"
id="firstName"
name="firstName"
placeholder="Enter the first name."
value={this.state.firstName}
onChange={(event) => setFirstName(event.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="lastName">LastName</label>
<input
type="text"
id="lastName"
name="lastName"
placeholder="Enter the last name."
value={this.state.lastName}
onChange={(event) => setLastName(event.target.value)}
/>
</div>
// Declare rest of fields here.
</form>
</div>
</div>
)
}

export default Home;

In the above code, you are able to see, that I have declared multiple states and also I have repeated the useState hook multiple times. If the supposed contact form has 10 more fields then we need to define the useState hook 10 more times and with that, the number of lines code will get an increase.
To avoid these number of lines of code you can do it this way.

Steps 1:

const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [emailAddress, setEmailAddress] = useState('');
const [phoneNumber, setPhoneNumber] = useState('');

||
||
||

// Above state declaration, you can define this way.
const initialContactFormState = {
firstName: '',
lastName: '',
emailAddress: '',
phoneNumber: '',
};
// With above object we can control multiple fields to add/remove for contact form

Steps 2:

// Now you can decalre the state using useState hooks from react;

import React, { useState } from 'react';

const [contactDetails, setContactDetails] = useState(initialContactFormState);
// This how we can reduce multiple state into one single object and declaring
// with the single useState hooks.

// And, when you want to access the state. you can do this way
{contactDetails.firstName};
{contactDetails.lastName};

// Or there is another best way to access the state, we can destructure the
// contactDetails object. something like this.

const [{
firstName,
lastName,
emailAddress,
phoneNumber
}, setContactDetails] = useState(initialContactFormState);

// With this we can access directly the state such as
{firstName}
{lastName}

Now, might be thinking, about how we can update the state in functional components. if we have declared the state as per the above code snippets. So, In the last steps, I can represent how you can update the states.

Final Steps :

// To update the state in functional components.
const onChangerHandler = (event) => {
const { name, value } = event.target;
setContactDetails(prevState => ({
...prevState,
[name]: value
}));
};
// This how you can update the state.

Full code:

// Home.jsx
import React, { useState } from 'react';

const Home = () => {
// Initial state of contact form.
const initialContactFormState = {
firstName: '',
lastName: '',
emailAddress: '',
phoneNumber: '',
};
// counter state.
const [counter, setCounter] = useState(0);
// Contact form, destructure states.
const [{
firstName,
lastName,
emailAddress,
phoneNumber
}, setContactDetails] = useState(initialContactFormState);

const handleIncrementCounter = () => {
setCounter(prevState => ({ counter: prevState + 1 }));
};

const handleDecrementCounter = () => {
setCounter(prevState => ({ counter: prevState - 1 }));
};

// To update the state in functional components.
const onChangerHandler = (event) => {
const { name, value } = event.target;
setContactDetails(prevState => ({
...prevState,
[name]: value
}));
};

return (
<div className="home-container">
<div className="counter-container">
<p>Counter : {counter}</p>
<button className="btn" onClick={() => handleIncrementCounter()}>Increment Counter</button>
<button className="btn" onClick={() => handleDecrementCounter()}>Decrement Counter</button>
</div>
<div className="container-contact-form">
<h3>Contact Form</h3>
<form>
<div className="form-group">
<label htmlFor="firstName">Firstname</label>
<input
type="text"
id="firstName"
name="firstName"
placeholder="Enter the first name."
value={this.state.firstName}
onChange={(event) => onChangerHandler(event)}
/>
</div>
<div className="form-group">
<label htmlFor="lastName">LastName</label>
<input
type="text"
id="lastName"
name="lastName"
placeholder="Enter the last name."
value={this.state.lastName}
onChange={(event) => onChangerHandler(event)}
/>
</div>
// Declare rest of fields here.
</form>
</div>
</div>
)
};

export default Home;

Conclusion

That’s for it now, With this small knowledge, you can have an idea to declare the state in React into functional components.

Let me know if this article is helpful for you Are there any certain features does one thinks I missed or should be covered? Let me know in the comments below!

Happy coding…!!!

--

--

Ishwar Deoolkar

Frontend Developer @Jeeves || jQuery || ReactJs Developer || VueJs Developer || Angular Developer || Software Engineer || GraphQL || Redux and Recoil || VueX