Hook

10 Mar 2024 . react .

Hooks are a new feature in React that allows us to manage state and side effects in functional components. Hooks are named functions that start with the word use and allow us to reuse stateful logic across components without having to write a class component.

Some common side effects include: fetching data from a server, subscribing to a data stream, logging values to the console, interval timers, and directly interacting with the DOM.

Hooks make our code more reusable, easier to understand, and easier to test.

Rules

  1. Only call Hooks from React function components.
  2. Only call Hooks at the top level, to be sure that Hooks are called in the same order each time a component renders.


State Hook

initialState is an optional value that can be used to set the value of currentState for the first render. The stateSetter  function is used to update the value of currentState  and rerender our component with the next state value.

const [currentState, stateSetter] = useState(initialState);


Effect Hook

We call this Hook at the top level of a React function definition to perform a side effect. The callback function that we pass as the first argument of useEffect() is where we write whatever JavaScript code that we’d like React to call after each render.

useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);


Cleanup Functions

If the effect does anything that needs to be cleaned up to prevent memory leaks, then the effect returns a cleanup function. The Effect Hook will call this cleanup function before calling the effect again as well as when the component is being unmounted from the DOM.

useEffect(() => {
  document.addEventListener('keydown', handleKeydown);
  return () => document.removeEventListener('keydown', handleKeydown);
});

Dependency Array

By default, with no dependency array provided, our effect is called after every render. An empty dependency array signals that our effect never needs to be re-run. A non-empty dependency array signals to the Effect Hook that it only needs to call our effect again when the value of one of the listed dependencies has changed.

useEffect(() => {
 alert('called after every render');
});
 
useEffect(() => {
 alert('called after first render');
}, []);
 
useEffect(() => {
 alert('called when value of `endpoint` or `id` changes');
}, [endpoint, id]);