React Hooks are a feature in React (starting from version 16.8) that allow you to use state and other React features without writing a class. Hooks are functions that let you "hook into" React state and lifecycle features from function components.
Key Features of React Hooks
- useState: Allows you to add React state to function components.
- useEffect: Performs side effects in function components.
- useContext: Accesses the context value without a provider.
- useReducer: A hook that gives you more fine-grained control over state than useState.
- useCallback: Returns a memoized callback.
- useMemo: Memoizes a value.
- useRef: Returns a mutable ref object whose
.current
property is initialized to the passed argument (initial value).
Example of useState
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Using useEffect for Side Effects
import React, { useEffect, useState } from 'react';
function Clock() {
const [date, setDate] = useState(new Date());
useEffect(() => {
const timer = setInterval(() => setDate(new Date()), 1000);
return () => clearInterval(timer);
}, []);
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}
Learn More
For more information on React Hooks, check out the official React documentation.
React Hooks