The Must-Know Hooks for Every React Developer!!

The Must-Know Hooks for Every React Developer!!

React Hooks have revolutionized the way we build React applications. They provide a way to handle state and side effects in functional components, making it easier to write and manage code. In this article, we will explore some of the most commonly used React Hooks that every React developer should know, with code examples written in TypeScript Programming Language.

1-The useState Hook

The useState hook is the most basic hook in React. It allows you to manage state in functional components. It takes an initial value as an argument and returns an array with two elements: the current state and a setter function to update it. Here is an example of how to use the useState hook.
</>Code Example:

```
import { useState } from 'react'
const Counter = () => {
const [count, setCount] = useState(0)
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount(prevCount => prevCount + 1)}>Increment</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>Decrement</button>
</>
)
}

```

In this example, we use the useState hook to create a state variable called count and initialize it to 0. Then, we use the setter function setCount to update the state when the Increment or Decrement buttons are clicked.

2-The useEffect Hook

The useEffect hook allows you to handle side effects in functional components, such as fetching data, subscribing to events, and updating the DOM. It takes two arguments: a function to run when the component mounts or updates and a list of dependencies.

</>Code Example:

```
import { useState, useEffect } from 'react'
interface User {
id: number
name: string
}
const fetchUser = async (id: number): Promise<User> => {
const response = await fetch(`https://userApi.com/users/${id}`) ) return response.json()
}
const UserProfile = ({ id }: { id: number }) => {
const [user, setUser] = useState<User | null>(null)
useEffect(() => {
let isMounted = true
fetchUser(id).then(user => {
if(isMounted) setUser(user)
})
return () => isMounted = false
}, [id])
if (!user) {
return <p>Loading...</p>
}
return <p>Name: {user.name}</p>
}
```
In this example, we use the useEffect hook to fetch the user data when the component mounts or the id prop updates. The function passed to useEffect uses the fetchUser function to fetch the data and the setter function setUser to update the state.

3-The useContext Hook

The useContext hook in React allows you to access context from anywhere in your component tree. This can be especially useful for situations where you need to share state or props between components that are not directly related.
</>Code Example:
```
import { createContext, useContext } from 'react';
interface MyContext {
count: number;
increment: () => void;
}
const MyContext = createContext<MyContext>({ count: 0, increment: () => {} });

// Provider component function
MyProvider({ children }: {
children: React.ReactNode}) {
const [count, setCount] = useState(0); const increment = () => setCount(count => count + 1);
return (
<MyContext.Provider value={{ count, increment }}> {children} </MyContext.Provider> );
}

// Consumer component function MyComponent() {
const { count, increment } = useContext(MyContext);
return ( <>
<button onClick={increment}>Increment</button>
<div>Count: {count}</div>
</> );
}
```
In this example, we first create a context object using the createContext function, and we specify the type of the context as MyContext. This interface defines the shape of the context object that we will be passing to the provider and consuming in the components. We then use the MyContext.Provider component to wrap the components that need to access the context, and pass the context object as a value prop. In the consuming component, we use the useContext hook to access the context object, and we use destructuring to extract the values that we need.

It's important to note that in order to use the useContext hook, the context object must be created at the top level of your application, such as in the root component, and it must be passed down through the component tree using the Provider component.

4-The useRef Hook

useRef is a hook in React that allows you to access and manipulate the DOM directly. It is used to store a reference to a DOM element or a component.
</>Code Example:

```
import { useRef } from 'react';
interface Props {
text: string;
}
const MyComponent: React.FC<Props> = ({ text }) => {
const inputRef = useRef<HTMLInputElement>(null); const handleClick = () => {
inputRef.current?.focus(); };
return (
<>
<input ref={inputRef} type="text" defaultValue={text} />
<button onClick={handleClick}>Focus Input</button>
</> );
};
```

In this example, useRef is used to create a ref called inputRef. The ref is passed as the ref attribute to an input element. The handleClick function is then able to use the current property of the ref to call the focus method on the input element, which will set focus on the input.

It's important to note that useRef will return an object with a current property initialized to the initialValue argument. This means that if you pass null as an initial value, the current property will be null until you assign a value to it.

5- The useLayoutEffect hook

is similar to useEffect, but it is executed synchronously after the layout is updated. This means that the useLayoutEffect hook will run before the browser paints the updated layout, whereas the useEffect hook runs after the paint. This can be useful for situations where you need to measure the layout of an element and update the state accordingly
</>Code Example:
```
import { useLayoutEffect } from 'react';

function MyComponent() {
const [size, setSize] = useState({ width: 0, height: 0 });

useLayoutEffect(() => {
const element = document.getElementById('my-element');
setSize({
width: element.offsetWidth,
height: element.offsetHeight
});
}, []);

return (
<div id="my-element">
Width: {size.width}px, Height: {size.height}px
</div>
);
}
```

6-The useMemo Hook

useMemo is a React hook that allows you to optimize the performance of a component by memoizing (caching) the results of expensive calculations. It takes two arguments: a function that performs the calculation, and an array of dependencies. The function is only re-run when one or more of the dependencies change.
</>Code Example:
```
import React, { useMemo } from 'react'; interface Props {
data: any;
}
const MyComponent: React.FC<Props> = ({ data }) => {
const memoizedValue = useMemo(() => {
// Do some expensive computation here return expensiveComputation(data);
}, [data]);
return <div>{memoizedValue}</div>;
};
export default MyComponent;
```
In this example, the useMemo hook is being used to memoize the result of the expensiveComputation function, which is only re-run when the data prop changes. This can help to improve the performance of the component by avoiding unnecessary re-co
mputations.

7-React Query Hook

React Query is a library that allows you to easily handle the fetching and caching of data in your React applications. It provides a set of hooks that can be used to manage and control the flow of data in your components.

One of the main hooks provided by React Query is the "useQuery hook". This hook allows you to easily fetch and cache data from an API and manage the state of the request (loading, error, and data).

</>Code Example:

```
import { useQuery } from 'react-query'; function MyComponent() {
const { status, data, error } = useQuery('users', async () => {
const response = await fetch('https://userApi.com/users');
return
;return) response.json();
});
if (status === 'loading') {
return <div>Loading...</div>;
}
if (status === 'error') {
return <div>Error: {error.message}</div>;
}
return (
<ul>
{data.map((user: any) => ( <li key={user.id}>{user.name}</li>
))}
</ul>
);
}
```

In this example, we are using the useQuery hook to fetch a list of users from a user API. We pass the useQuery hook two arguments: the first is a key that identifies the query, and the second is a function that returns a promise that resolves with the data. The hook returns an object with the current status of the request, the data, and the error if any.

In the component, we check the status of the request and render the appropriate UI. If the request is loading, we display a loading message. If there's an error, we display the error message. If the request is successful, we display the data in a list.

Additionally, React Query also provides other hooks like useMutation for making data updates, useInfiniteQuery for pagination and useIsFetching for real-time fetching state.

Summary

React hooks are a powerful feature that allow developers to manage state and perform side effects in functional components. Some of the most commonly used hooks include useState, useEffect, useContext,useMemo,useLayoutEffect and useQuery hook.
These hooks are essential for developing efficient and maintainable React applications. By utilizing them, you can simplify your code and improve the performance of your components.

I hope you find this informative :)