Skip to content

Instantly share code, notes, and snippets.

@MainakRepositor
Created July 16, 2024 06:56
Show Gist options
  • Save MainakRepositor/0da1a9e755c9cfd5f2a9fb9f8c14bfb9 to your computer and use it in GitHub Desktop.
Save MainakRepositor/0da1a9e755c9cfd5f2a9fb9f8c14bfb9 to your computer and use it in GitHub Desktop.
React Hooks
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