Created
July 16, 2024 06:56
-
-
Save MainakRepositor/0da1a9e755c9cfd5f2a9fb9f8c14bfb9 to your computer and use it in GitHub Desktop.
React Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
React Hooks are functions that let you use state and other React features without writing a class. Introduced in React 16.8, hooks simplify the process of managing component state and side effects. | |
Here's a brief overview of two commonly used hooks: | |
1. **useState**: This hook lets you add state to functional components. You call `useState` and pass the initial state value. It returns an array with two elements: the current state and a function to update it. | |
```javascript | |
const [count, setCount] = useState(0); | |
``` | |
In this example, `count` is the state variable, and `setCount` is the function to update `count`. | |
2. **useEffect**: This hook lets you perform side effects in function components, such as data fetching, subscriptions, or manually changing the DOM. It takes two arguments: a function that contains the side-effect logic and an optional array of dependencies. | |
```javascript | |
useEffect(() => { | |
document.title = `Count: ${count}`; | |
}, [count]); | |
``` | |
Here, the document title updates every time `count` changes. | |
Hooks allow for cleaner, more readable code by keeping related logic together and making it easier to reuse stateful logic across different components. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment