React Fundamentals

0% completed

Previous
Next
useEffect Dependency Array

useEffect's Dependency Array

The dependency array of useEffect defines the variables or values that the effect depends on. When any of these dependencies change, the effect will be re-run. Here are some examples of what can be included in the dependency array:

  1. State variables

    Any state variable in your component can be included as a dependency. This allows the effect to re-run when the state changes.

Example:

useEffect(() => { // Effect runs when `searchQuery` changes }, [searchQuery]);
  1. Props

If your component receives props, you can include them in the dependency array. This ensures that the effect re-runs when props change.

Example:

useEffect(() => { // Effect runs when `userId` prop changes }, [userId]);
  1. Computed values (derived from state or props)

    Any values derived from state or props, such as a calculated value or result of a function, can be dependencies.

    Example:

const derivedValue = state.someValue + props.someProp; useEffect(() => { // Effect runs when derivedValue changes }, [derivedValue]);
  1. Functions

    Functions that are defined outside of the useEffect or inside the component (depending on whether the function's identity changes) can be dependencies.

    Example:

const handleClick = () => { // Some action }; useEffect(() => { // Effect runs when `handleClick` function changes }, [handleClick]);
  1. Refs

    Refs can be included in the dependency array, but they generally don't trigger a re-render, so you typically only need to use refs in a way that doesn't affect the behavior of the effect directly. Use refs in dependency array sparingly.

    Example:

const inputRef = useRef(); useEffect(() => { // Effect runs when `inputRef` changes }, [inputRef]);
  1. Custom hooks

    If you use custom hooks that return state or values, those values may need to be included in the dependency array to ensure proper reactivity.

    Example:

const { data } = useCustomHook(); useEffect(() => { // Effect runs when data changes }, [data]);
  1. Array or Object Values

    If you are using arrays or objects as dependencies, ensure that they are not re-created on every render (such as when using useEffect or state updates that recreate them). Example:

const values = [1, 2, 3]; useEffect(() => { // Effect runs when `values` changes }, [values]);

This may cause unnecessary re-renders.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next