0% completed
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:
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]);
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]);
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]);
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]);
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]);
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]);
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.
.....
.....
.....