Functional Component Deep Dive
Functional components are JavaScript functions that accept props as an argument and return React elements (JSX) to define the UI. They are simpler and more concise than class components, making them easier to write and understand.
Example:
import React from'react';
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default Greeting;
In this example:
- The
Greetingfunction is a functional component. - It accepts
propsas an argument and uses them to display dynamic content. - It returns JSX, which React renders to the DOM.
Key Features of Functional Components
1. Stateless by Nature
Before React Hooks, functional components were considered "stateless" because they could not manage their own state or lifecycle methods. However, with the introduction of Hooks, functional components can now handle state and side effects, making them just as powerful as class components.
2. Props
Functional components receive data from their parent components through props. Props are immutable and allow components to be reusable and dynamic.
Example:
function Welcome(props) {
return <h1>Welcome,{props.name}!</h1>;
}
export default Welcome;
3. React Hooks
React Hooks, introduced in React 16.8, allow functional components to manage state, handle side effects, and access other React features without converting them into class components.
Below are the available Hooks in React Js
Basic Hooks
useState
- Purpose: Manages state in functional components.
- Use Case: Tracking variables like counters, form inputs, or toggles.
const [count, setCount] = useState(0);
useEffect
- Purpose: Handles side effects such as data fetching, subscriptions, or DOM updates.
- Use Case: Fetching data from an API, setting up event listeners, or cleaning up resources.
// Example 1
useEffect(() => {
console.log('Component mounted');
return() =>console.log('Cleanup on unmount');
},
[]);
As per above example useEffect Hook execute before rendering the component.
Lets consider another example
// Example 2
useEffect(() => {
console.log('Component mounted');
return() =>console.log('Cleanup on unmount');
},
[url]);
If we compare Example 1 and Exaample 2 we notice 1st Example is blank array while in second array there is 'url'.
Blank array indicate this hooks will execute one time during component render, while in second example indicates if anything changes occur in url then this hook will be rerender.
useContext
- Purpose: Accesses values from a React context without using
Context.Consumer. - Example Use: Sharing global data like themes or authentication status.
Syntax:
const value = useContext(MyContext);
Additional Hooks
- useReducer
- useCallback
- useMemo
- useRef
- useImperativeHandle
Advanced Hooks
- useLayoutEffect
- useDebugValue
