DEV Community

Cover image for React hooks
Dezina
Dezina

Posted on • Edited on

React hooks

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. Hooks allow to easily manipulate the state of our functional component without needing to convert them into class components.

useEffect
The first one is a callback (a function), and the second one is the dependency array. It takes the form of an array of variables. The React hooks that have dependency arrays are useEffect, useLayoutEffect, useCallback, useMemo.
https://devtrium.com/posts/dependency-arrays

  • The dependency array basically tells the hook to "only trigger when the dependency array changes".
    useEffect(() => {
    // this will run if counter1 OR counter2 changes
    console.log('Either counter1 or counter2 changed (or both');
    }, [counter1, counter2]);

  • Empty dependendy array means that the hook will only trigger once when the component is first rendered.
    useEffect(() => {
    console.log('I will run only once');
    }, []);

  • The rule is: if any variable is used inside the hook but is defined outside of it, then it should go in the dependency array.

  • The goal of the dependency array is to make the hook trigger when one of the values changes. There's no point putting stuff in there that won't change.

useState
The first parameter is the state & second parameter is used to change/update the state using setState. useState Hook does not update immediately.
const [count, setCounter] = useState(0);
useParams()

The react-router-dom package has useParams hooks that let you access the parameters of the current route. This is only to get the url paramerters. URL parameters are the ones that appear before the ? in the URL.
import {useParams} from "react-router-dom";
const { jobId } = useParams();
console.log("jobId", jobId)
Enter fullscreen mode Exit fullscreen mode

useLocation

The useLocation hook is a function that returns the location object that contains information about the current URL. Whenever the URL changes, a new location object will be returned. It is also used to get query parameter of the url.
Location object properties:

hash: the anchor part (#)
pathname: the path name
search: the query string part
state
key
_example:_
const search = useLocation().search;
const candId = new URLSearchParams(search).get('candId');
console.log("candId", candId)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)