State in React JS
State in React is an object that stores a componentβs dynamic data β data that can change over time.
When the state changes, React re-renders the component automatically to update the UI.
Use of State
To store dynamic data inside a component.
To update the UI automatically when data changes.
To handle user inputs and form values.
To show or hide elements (toggle visibility).
To manage component behavior like buttons, themes, and counters.
Simple Example
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0); // state
return (
<>
<p>Count: {count}
<button onClick={() => setCount(count + 1)}>Increase</button>
</>
);
}
What is Hooks
Hooks in React are special functions that allow you to use state, lifecycle features, and other React capabilities inside functional components (without using classes).
They make components more powerful, reusable, and easier to write.
useState β for storing data
const [count, setCount] = useState(0);
app.js
import './App.css';
import Navbar from './components/Navbar';
import TestForm from './components/TestForm';
function App() {
return (
<>
<Navbar name="The Royal Coding" about_us="About us TRC"/>
<TestForm heading="Enter the Text to Convert to Uppercase"/>
</>
);
}
export default App;
TestForm.js
import React, {useState} from 'react'
export default function TestForm(props) {
let handleupCase = ()=>{
let new_text = text.toUpperCase()
newText(new_text)
}
let handlechange = (event)=>{
newText(event.target.value)
}
const [text, newText] = useState("");
return (
<>
<div className='container'>
<div className="mb-3">
<h1 className='my-3 py-2'>{props.heading}</h1>
<textarea
className="form-control"
value={text}
onChange={handlechange}
id="exampleFormControlTextarea1"
rows="8"></textarea>
</div>
<button
type="button"
className="btn btn-primary"
onClick={handleupCase}>
Convert to Uppercase
</button>
</div>
</>
);
}