React hooks allows us to use the features of a class component like state and lifecycles in a functional component. We can import the hooks from react to use them.
We need to follow these rules when using them:
The built-in Hooks can be divided into two parts:
Basic Hooks
useState
useEffect
useContext
Additional Hooks
useReducer
useCallback
useMemo
useRef
useImperativeHandle
useLayoutEffect
useDebugValue
We can also create our custom hooks. A custom Hook is just like a regular function that starts with "use" and can call other Hooks. It follows the rules of Hooks.
Here is a simple counter app that uses useState
to manage the state.
import React, {useState} from 'react' //import the hook
function Example() {
const [value, setValue] = useState(0) //initialize useState
const handleDecrement = () => {
setValue(value - 1); // modify state
}
const handleIncrement = () => {
setValue(value + 1) //modify state
}
return (
<div>
<button onClick={handleDecrement}>-</button>
<span>{value}</span> // read state
<button onClick={handleIncrement}>+</button>
</div>
)
}
export default Example