What are Hooks in React?
React Hooks are functions that allow functional components to use state and other React features that were previously only available in class components.
1. What are usestate hooks in React?
- usestate is one of the hooks in react
- usestate hooks to allow maintaining state in react
- State refers to data that can change over time and affect what is displayed on the page.
- usestate refers to an array with two elements
- current state value
- function to update that value
The syntax for useState is as follows,
const [state, setState] = useState(initialState);
- state refers current value
- setstate refers function that allows you to update the state value
- initialState is the initial value for the state.
- You can call the setState function with a new value, and React will re-render the component with the updated state value
- useState can be used multiple times in a component to manage different parts of states
For example, the following code creates a component with a state value count that is initialized to 0 and a button that updates the count value when clicked:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
Okay, budy's, we will see a real-time Example using react sample form.
import React, { useState } from "react";
const UseState = () => {
return (
<div>
<form className="p-5">
<div>
<label htmlFor="">
Name:
<input type="text" />
</label>
</div>
<div>
<label htmlFor="">
Age:
<input type="number" />
</label>
</div>
<div>
<label htmlFor="">
Gender:
<input type="text" />
</label>
</div>
</form>
</div>
);
};
This example is how I get value from each field, and once onchange the field, that's time to play the usestate. Let us go to the example,
import React, { useState } from "react";
const UseState = () => {
const [name, setName] = useState("");
const [age, setAge] = useState(0);
const [gender, setGender] = useState("");
return (
<div>
<form className="p-5 bg-red-300">
<div>
<label htmlFor="">
Name:
<input type="text" onBlur={(event) => setName(event.target.value)} />
</label>
</div>
<div>
<label htmlFor="">
Age:
<input type="number" onBlur={(event) => setAge(event.target.value)} />
</label>
</div>
<div>
<label htmlFor="">
Gender:
<input type="text" onBlur={(event) => setGender(event.target.value)} />
</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>
);
};
Then use value everywhere in your application.
2. What are useeffect hooks in React?
- useEffect is a hook in React that allows you to perform side effects in functional components.
- Side effects are actions that affect the outside world, such as fetching data from an API, updating the DOM, or setting up event listeners.
- The useEffect hook takes two arguments: a callback function and an optional dependencies array.
- The callback function is executed after the component has rendered and can contain any side effects that you want to perform.
- The dependencies array is used to specify when the effect should be re-run.
- If the dependencies array is empty, the effect will only be run once when the component mounts.
1. No dependency passed
useEffect(() => {
//Runs on every render
});
2. An empty array
Here's an example of using useEffect to fetch data from an API when a component mounts:
import { useState, useEffect } from 'react';
function useEffect() {
const [data, setData] = useState(null);
useEffect(() => {
async function fetchData() {
const response = await fetch('https://myapi.com/data');
const data = await response.json();
setData(data);
}
fetchData();
}, []); // empty dependencies array means run once when component mounts
return (
<div>
{data ? (
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
) : (
<p>Loading data...</p>
)}
</div>
);
}
3. Value passed
useEffect runs on every render. That means a render happens when the count changes, which triggers another effect.
function Counter() {
const [count, setCount] = useState(0);
const [calculation, setCalculation] = useState(0);
useEffect(() => {
setCalculation(() => count * 2);
}, [count]); // That means that when the count changes, a render happens, which then triggers another effect.
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>+</button>
<p>Calculation: {calculation}</p>
</>
);
}
//Runs on the first render
//And any time any dependency value changes
Conclusion
The useEffect and useState hooks in React provide a powerful and concise way to manage state and perform side effects in functional components. Using these hooks, developers can write more concise and expressive code and efficiently manage complex state and component interactions. If you have any queries, ask me in to comment section.