React.js Hooks
What is Hooks in React.js:
React Hooks are functions that enable functional components to use state and other React features without writing a class.
They were introduced in React 16.8 as a way to simplify state management and side-effect handling in React applications.
Some of the most commonly used React Hooks:
useState(): Allows functional components to manage local state. It returns a stateful value and a function to update it.
Also you can call useState() multiple times to manage multiple pieces of state within a component.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
useEffect(): An allows to make that effect content methods.
To compare to rerenderer, it's the wreathing of componentDidMount, componentDidUpdate and componentWillUnmount events in a single lifecycle method.
useEffect() runs after each rendering as it is default, but you can perform specific dependency if you want it to run in a defined time.
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
useContext(): Provides a way to consume context within a functional component.
It accepts a context object (created using React.createContext()) and returns the current context value.
import React, { useContext } from 'react';
import MyContext from './MyContext';
function MyComponent() {
const value = useContext(MyContext);
return <div>{value}</div>;
}
These are just a few examples of React Hooks.
Others like useRef(), useCallback(), useMemo(), useReducer(), and custom hooks can be used to further simplify state management, side-effect handling, and code organization in functional components.