DEV Community

Pedro Uzcátegui
Pedro Uzcátegui

Posted on • Updated on

React Hooks

React Hooks were introduced on React 16.8 by Dan Abramov, the creator of React.js

Hooks are a series of features that allows developers to use certain functionalities that were impossible in plain react function components.

We have a series of pre-defined hooks that react offers us, but we also can create our own hooks.

  • useState
  • useEffect
  • useContext
  • useReducer
  • useCallback
  • useMemo
  • useRef
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue

And we also will create 3 example custom hooks for our projects.

We will explain the hooks and then move into a project only using hooks.

Let's see the React.js hooks rules:

  1. Call Hooks only on the superior level:
    You can't call hooks in cycles, conditionals, or nested functions

  2. Call Hooks only on React Functional Components or custom hooks

The list of pre-defined hooks we will explore will be:

  1. useState

  2. useEffect

The useEffect hooks is used on data request, subscriptions and manual actualizations. These ones are called "secondary effects"

If you're familiar with React Class Components, then, you will use the useEffect hook to handle the following lifecycle methods: componentDidMount, componentDidUpdate, componentWillUnmount.

Also, there are 2 types of secondary effects, those who requires sanitizing operation and other who don't.

  • Those who do not require sanitizing: Those hooks which we can execute and forget about them, for example: Network Requests, Manual DOM Mutations, Register

  • Those who require sanitizing: We sanitize effects that could lead to a memory leak

Effects run at every render, so we use the useEffect hook to reeplace some lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount)

Returning a function inside the useEffect to indicate react how to sanitize a effect (clean, unmount)

We usually use the useEffect with state variables.

Omiting effects to optimize rendering: If you do not want to run the effect every time the component is updated, then you should consider using the second argument of the hook, the dependency array.

const [count, setCount] = useState(0)

useEffect(()=>{
   setCount(count + 1)
},[count])
Enter fullscreen mode Exit fullscreen mode

This effect will run only and if only the count state variable value changes.

We can add more values to it

If we leave the dependency array empty, it will only run once

Top comments (0)