React Hooks Basics
Hooks were added to React in version 16.8.
Hooks allow function components to have access to state and other React features. Because of this, class components are generally no longer needed.
📌 State Hook
🎈useState() is a Hook that lets you add a piece of state to your component.
useState accepts an initial state and returns two values:
- The current state.
- A function that updates the state.
const [count, setCount] = useState(0);
The useState Hook can be used to keep track of strings, numbers, booleans, arrays, objects, and any combination of these!
🎈useReducer Hook is similar to the useState Hook. It allows for custom state logic.
The useReducer(reducer, initialState) hook accept 2 arguments: the reducer function and the initial state. The hook then returns an array of 2 items: the current state and the dispatch function.
import { useReducer } from 'react';function MyComponent() {const [state, dispatch] = useReducer(reducer, initialState);const action = {type: 'ActionType'};return (<button onClick={() => dispatch(action)}>Click me</button>);}
📌 Effect Hook
🎈useEffect() Hook allows you to perform side effects in your components.
Some examples of side effects are: fetching data, directly updating the DOM, and timers.
useEffect accepts two arguments. The second argument is optional.
Dependencies argument of useEffect(callback, dependencies) lets you control when the side-effect runs. When dependencies are:
- Not provided: the side-effect runs after every rendering.
- An empty array []: the side-effect runs once after the initial rendering.
- Has props or state values [prop1, prop2, …, state1, state2]: the side-effect runs only when any depenendecy value changes
Some side-effects need cleanup: close a socket, clear timers.
If the callback of useEffect(callback, deps) returns a function, then useEffect() considers this as an effect cleanup:
Cleanup works the following way:
- After initial rendering, useEffect() invokes the callback having the side-effect. cleanup function is not invoked.
- On later renderings, before invoking the next side-effect callback, useEffect() invokes the cleanup function from the previous side-effect execution (to clean up everything after the previous side-effect), then runs the current side-effect.
- Finally, after unmounting the component, useEffect() invokes the cleanup function from the latest side-effect.
📌 Callback Hook
The React useCallback
Hook returns a memoized callback function.
This allows us to isolate resource intensive functions so that they will not automatically run on every render.
The useCallback
Hook only runs when one of its dependencies update. This can improve performance.
Hence, in the folowing example the useCallbakc hook helps not to rerender child everytime we increment the count.
const App = () => {
const [count, setCount] = useState(0);
const [todos, setTodos] = useState([]);
const increment = () => {
setCount((c) => c + 1);
};
const addTodo = useCallback(() => {
setTodos((t) => [...t, "New Todo"]);
}, [todos]);
return (
<>
<Todos todos={todos} addTodo={addTodo} />
<hr />
<div>
Count: {count}
<button onClick={increment}>+</button>
</div>
</>
);
};
📌 useRef Hook
The useRef
Hook allows you to persist values between renders.
It can be used to store a mutable value that does not cause a re-render when updated.
It can be used to access a DOM element directly.
If we tried to count how many times our application renders using the useState
Hook, we would be caught in an infinite loop since this Hook itself causes a re-render.
New Hooks are coming …