Functional Components with Hooks in React

 Functional Components with Hooks in React

Functional components are a simpler way to write React components that only contain a render method and do not manage their own state or lifecycle methods. With the introduction of Hooks in React 16.8, functional components can now manage state and side effects, making them more powerful and versatile.

This guide will cover the key concepts of functional components and how to use Hooks effectively.


1. What are Functional Components?

Functional components are JavaScript functions that return JSX. They are often referred to as "stateless" components because they do not manage their own state, although this is no longer the case with Hooks.

Example of a Simple Functional Component:

javascript

import React from 'react'; const Greeting = () => { return <h1>Hello, World!</h1>; }; export default Greeting;

2. Introduction to Hooks

Hooks are special functions that let you “hook into” React state and lifecycle features from functional components. The two most commonly used Hooks are useState and useEffect.

3. The useState Hook

The useState Hook allows you to add state to your functional components.

How to Use useState

  1. Import useState from React.
  2. Call useState within your functional component to declare a state variable.

Example:

javascript

import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); // Declare a state variable 'count' and a setter function 'setCount' const increment = () => { setCount(count + 1); // Update state }; return ( <div> <h1>{count}</h1> <button onClick={increment}>Increment</button> </div> ); }; export default Counter;

4. The useEffect Hook

The useEffect Hook lets you perform side effects in your functional components. It’s the equivalent of lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount.

How to Use useEffect

  1. Import useEffect from React.
  2. Call useEffect within your component to perform side effects.

Example:

javascript

import React, { useState, useEffect } from 'react'; const Timer = () => { const [count, setCount] = useState(0); useEffect(() => { const timer = setInterval(() => { setCount((prevCount) => prevCount + 1); // Update state every second }, 1000); return () => clearInterval(timer); // Cleanup function to clear the timer }, []); // Empty dependency array means this effect runs only once return <h1>{count}</h1>; }; export default Timer;

5. Dependency Array in useEffect

The second argument of useEffect is the dependency array. It allows you to control when the effect runs:

  • Empty Array []: The effect runs only once when the component mounts.
  • With Dependencies [dep1, dep2]: The effect runs whenever any of the dependencies change.
  • Without a Second Argument: The effect runs after every render.

Example with Dependencies:

javascript

import React, { useState, useEffect } from 'react'; const Example = () => { const [count, setCount] = useState(0); useEffect(() => { console.log(`Count has changed: ${count}`); }, [count]); // Effect runs only when 'count' changes return <button onClick={() => setCount(count + 1)}>Increment</button>; }; export default Example;

6. Multiple useEffect Hooks

You can use multiple useEffect hooks in a single component to separate different side effects.

Example:

javascript

const Example = () => { const [count, setCount] = useState(0); const [name, setName] = useState(''); useEffect(() => { console.log(`Count has changed: ${count}`); }, [count]); useEffect(() => { console.log(`Name has changed: ${name}`); }, [name]); return ( <div> <button onClick={() => setCount(count + 1)}>Increment</button> <input value={name} onChange={(e) => setName(e.target.value)} /> </div> ); };

7. Other Built-in Hooks

In addition to useState and useEffect, React provides several other built-in hooks:

  • useContext: Allows you to use the React Context API to share data between components without passing props.
  • useReducer: A more powerful alternative to useState for managing complex state logic.
  • useCallback: Returns a memoized callback function, useful for optimizing performance.
  • useMemo: Returns a memoized value, useful for optimizing expensive calculations.
  • useRef: Provides a way to directly access a DOM element or keep a mutable reference.

8. Example of Using Multiple Hooks Together

Here’s a complete example combining multiple hooks:

javascript

import React, { useState, useEffect, useRef } from 'react';
const SearchComponent = () => { const [query, setQuery] = useState(''); const [results, setResults] = useState([]); const inputRef = useRef(null); useEffect(() => { // Fetch data based on the query if (query) { fetch(`https://api.example.com/search?q=${query}`) .then(response => response.json()) .then(data => setResults(data.results)); } }, [query]); // Fetch results when 'query' changes const handleClear = () => { setQuery(''); setResults([]); inputRef.current.focus(); // Focus on the input field }; return ( <div> <input ref={inputRef} value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search..." /> <button onClick={handleClear}>Clear</button> <ul> {results.map(result => ( <li key={result.id}>{result.name}</li> ))} </ul> </div> ); }; export default SearchComponent;


Post a Comment

1 Comments