-
React Hooks are inbuilt functions provided by React that allow functional components to use state and lifecycle features.
-
Before Hooks, class components lifecycle methods were used to maintain state in React applications.
-
To use React Hook first we first have to import it from React library:
// Import Hook from the React library
import React, { useState } from "react";
- useState: State
- useEffect: Side effects
- useContext: Context
- useReducer: Complex state
- useCallback: Memoization
- useMemo: Performance
- useRef: Refs
- useLayoutEffect: Synchronous Side effects
- "state" refers to the current data of the component.
- Stateful or state management means, when a user performs some actions on the UI, then the React application should be able to
update and re-render that data or state
on the UI.
import React from "react";
// Stateless Example
function ComponentState() {
let count = 0; // Initial state
const increment = () => {
count += 1; // State updated
console.log(`Count: ${count}`);
};
return (
<div>
<p>Stateless Example</p>
<p>Count: {count}</p> {/* Not updating */}
<button onClick={increment}>Click</button>
</div>
);
}
export default ComponentState;
-
The useState hook enables functional components to
manage state
. -
useState() working: useState() function accepts the initial state value as the parameter and returns an array with two elements:
- The first element is the current state value (count in this code).
- Second element is the function that is used to update the state (setCount in this code).
-
The concept of assigning array elements to individual variables is called
array destructuring
.
// state is the current state value.
// setState is a function that used to update the state.
const [state, setState] = useState(initialValue);
import React, { useState } from "react";
function UseState() {
// array destructuring
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
console.log(`Count: ${count + 1}`);
};
return (
<div>
<p>Stateful Example</p>
<p>Count: {count} {/* Updating */}</p>
<button onClick={increment}>Click</button>
</div>
);
}
export default UseState
- The useEffect Hook in React is used to perform side effects in functional components.
- For example, data fetching from API, subscriptions, or any other operation that needs to be performed after the component has been rendered.
2 points to remember about useEffect():
- useEffect() is called after the component renders. Example, side effects.
- useEffect() function will accept two parameters: (Effect function, dependency array).
import React, { useEffect } from "react";
function UseEffect() {
useEffect(() => {
const fetchData = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const result = await response.json();
console.log("Title:", result.title);
};
fetchData();
}, []);
return(
<div>
<p>Data is being fetched ...</p>
</div>
)
}
export default UseEffect;
Dependencies arrays (optional) act as triggers for useEffect to rerun; meaning if any of dependencies values change, the code inside useEffect() will be executed again.
useEffect(() => {
// Side effect code here
// Optional cleanup code
return () => {
// Cleanup code here
};
}, [dependencies]);
An empty array[] indicates that the effect function should only run once
function UseEffect() {
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const result = await response.json();
setData(result);
};
fetchData();
}, []);
return (
<div>
<p>Title: {data.title}</p>
</div>
);
}