What are React hooks and name a few commonly used ones?

clock icon

Asked 1 year ago

message icon

1

eye icon

3

While building my React application, I came across the term “hooks” in multiple tutorials and documentation. From what I understand, they seem to be functions that allow you to use React features without writing a class, but I’m still not fully clear on how they work or what problems they solve.

1 Answer

1. useState

Allows you to add local state to a functional component.

1import { useState } from 'react';
2
3function Counter() {
4 const [count, setCount] = useState(0);
5
6 return (
7 <button onClick={() => setCount(count + 1)}>
8 You clicked {count} times
9 </button>
10 );
11}
1import { useState } from 'react';
2
3function Counter() {
4 const [count, setCount] = useState(0);
5
6 return (
7 <button onClick={() => setCount(count + 1)}>
8 You clicked {count} times
9 </button>
10 );
11}

2. useEffect

Used to perform side effects in your components (like fetching data, setting up subscriptions, or manually changing the DOM).

1useEffect(() => {
2 console.log('Component mounted or updated');
3}, []); // Empty dependency array = run only once on mount
1useEffect(() => {
2 console.log('Component mounted or updated');
3}, []); // Empty dependency array = run only once on mount

3. useContext

Gives you access to context values without having to wrap your component with a Consumer.

1const user = useContext(UserContext);
1const user = useContext(UserContext);

4. useRef

Provides a way to reference DOM elements or persist mutable values across renders.

1const inputRef = useRef(null);
1const inputRef = useRef(null);

5. useMemo and useCallback

Used to optimize performance by memoizing expensive computations or functions.


1

Write your answer here

Top Questions