DIFFERENCE BETWEEN HTML AND XML:
React Hooks
- Hooks allow functions to have access to state and other React features without using classes.
- They provide a more direct API to React concepts like props, state, context, refs, and lifecycle.
What is a Hook?
Hooks are functions that let you "hook into" React state and lifecycle features from functional components.
You must import Hooks from react.
Here we are using the useState Hook to keep track of the application state.
State generally refers to application data or properties that need to be tracked.
React useState Hook
- The React useState Hook allows us to track state in a function component.
- State generally refers to data or properties that need to be tracking in an application.
Import useState
- To use the useState Hook, we first need to import it into our component.
import { useState } from "react";
Initialize useState
- We initialize our state by calling useState in our function component.
- useState accepts an initial state and returns two values:The current state.
A function that updates the state.
Example:Initialize state at the top of the function component.
import { useState } from "react";
function FavoriteColor() {
const [color, setColor] = useState("red");
}
Update State
- To update our state, we use our state updater function.
Example:
- Use the state updater function to update the state:
<button
type="button"
onClick={() => setColor("blue")}
>Blue</button>
State can contain:
- The useState Hook can be used to keep track of strings, numbers, booleans, arrays, objects, and any combination of these!
We could create multiple state Hooks to track individual values.
Updating Objects and Arrays in StateWhen state is updated, the entire state gets overwritten.
What if we only want to update the color of our car?If we only called setCar({color: "blue"}), this would remove the brand, model, and year from our state.
We can use the JavaScript spread operator to help us.
Example:
- Use the JavaScript spread operator to update only the color of the car:
const updateColor = () => {
setCar(previousState => {
return { ...previousState, color: "blue" }
});
}
TASK ON REACT-JS:
Task-01
- Counter program :
import { useState } from "react"
function Counter(){
const [count, setCount] = useState(0);
function increment(){
setCount(count + 1)
}
function decrement(){
setCount(count - 1)
}
function reset(){
setCount(0)
}
return(
<div className="div">
<h1>Counter App</h1>
<h3>Count: {count}</h3>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>reset</button>
</div>
)
}
export default Counter;
OUTPUT:


Top comments (0)