score:0
In your case there is no side-effect, it's just data derived from state, so you should use different tools instead of useEffect
.
First filter could be implemented with just getting value by key:
const carsByBrand = allCars[brand];
Complexity of this operation is constant, so memoization will be too expensive.
And second filter is debounced, but you might want to memoize it because of filtering with linear complexity. For these purposes you can use for example useDebouncedMemo hook:
const filteredCars = useDebouncedMemo(() => {
return carsByBrand.filter(model => model.startsWith(filterKey)
}, [filterKey, carsByBrand], 500)
In this case dependencies of hook are exhaustive and logic is much more declarative.
score:2
Yes, you should follow this rule all the time, when you find your code break with following it, that means good practice is not followed. That is the meaning of this rule, make sure you design code well.
I imagine in your case the code looks like this:
const Test = () => {
const [wantToSync] = useState(0)
const [notWantToSync] = useState(0) // notWantToSync also might come from props, i'll use state as example here
useEffect(() => {
fetch('google.com', {
body: JSON.stringify({wantToSync, notWantToSync})
}).then(result => {
// ...
})
}, [wantToSync]) // component is supposed to be reactive to notWantToSync, missing notWantToSync in dep is dangerous
}
If notWantToSync
was defined as a state of the component, the component is supposed to be reactive to it, including useEffect
. If that is not what you want, notWantToSync
shouldn't be state from start.
const Test = () => {
const [wantToSync] = useState(0)
const notWantToSyncRef = useRef(0) // hey I don't want notWantToSync to be reactive, so i put it in useRef
useEffect(() => {
fetch('google.com', {
body: JSON.stringify({wantToSync, notWantToSync: notWantToSyncRef.current})
}).then(result => {
// ...
})
}, [wantToSync, notWantToSyncRef]) // yeah, now eslint doesn't bother me, and notWantToSync doesn't trigger useEffect anymore
}
Normally you don't need to do if else in useEffect to stop re-rendering, there're other approaches like useMemo
or useCallback
to do similar things in addition to useRef
although they have different using context.
I see your struggle in the new example, so you want to do a throttle, and if filterKey
is added to the first useEffect dep, the throttle will be broken. My opinion is that when you find yourself in a situation like this, that often means there's better practice(eslint exhaustive help to identify it), for example, extract throttle logic to a hook: https://github.com/streamich/react-use/blob/master/src/useThrottle.ts.
Exhaustive deps is not something vital to follow, it's just a good practice to make sure your code is designed well. The above example proves it that
Source: stackoverflow.com
Related Query
- Does the dependency array in React hooks really need to be exhaustive?
- does react really need nodeJS on the frontend ENV?
- React hooks: why does useEffect need an exhaustive array of dependencies?
- React useEffect - passing a function in the dependency array
- How does React Hooks useCallback "freezes" the closure?
- React Hook useEffect has missing dependencies. Either include them or remove the dependency array
- React does not refresh after an update on the state (an array of objects)
- Should you pass setter functions into the dependency array of a React hook?
- Changing object property in an array with React Hooks does not evoke a re-render
- React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array react-hooks/exhaustive-deps
- why filtering state array with react hooks doesn't work but filtering original array does
- react hook useeffect has missing dependencies: yyy. either include them or remove the dependency array react-hooks/exhaustive-deps
- Does it hurt performance to use the react redux hooks in a list?
- React hooks useState/setState not working after sorting the array and passing it
- What is the benefit of having $sce or Strict Contextual Escaping in angularjs and why react does not need to do it?
- React Hook useCallback has an unnecessary dependency: 'price'. Either exclude it or remove the dependency array react-hooks/exhaustive-deps
- useState react hook does not set the array state
- React Hook useEffect has missing dependencies: 'colors' and 'options'. Either include them or remove the dependency array
- React Hooks: Why does the exhaustive-deps linter rule want a local function used in useMemo in the dependency list?
- React hooks how to only execute side effect function only once if I need to update 2 dependency variables
- React hooks dependency array vs. TypeScript discriminated unions
- React 16.8 hooks => how to properly inject an array of elements into the DOM
- Does props.history.listen in React Router need to be cleaned up in useEffect? If so, what is the right way to do it?
- Eslint React Hooks Error: eslint-plugin-react-hooks exhaustive deps warning for a function dependency in useEffect
- In React, when using map() to loop through an array of elements, does the result need to only be displayed using the <ul> and <li> tags?
- React hooks useState initialization does not reset the state
- React Hook useCallback has a missing dependency: 'Id'. Either include it or remove the dependency array
- How to sort the array in React Hooks using UseState
- React Hooks useState Array empty with states rendered in the component
- React Hooks Form Handling: Update the state of an object with multiple string items and one array item
More Query from same tag
- React make two async requests and passing the state
- Is it OK to un-subscribe and re-subscribe all my @Lexical/react command listeners on every render?
- Event.target.value is returning undefined
- react-google-maps HeatmapLayer undefined
- Misunderstanding on how reactJS properties work
- Use async login function in react context
- Object Array with dates, tallied together for each month
- In the Redux tutorial, running index.js, how do I avoid "ReferenceError: document is not defined"
- How do get the value of only checked checkboxes in Javascript?
- How do I change the style of the inner part enclosed by the lines(polar) chart created with highcharts?
- Add URL Validation to TagsInput
- React import package get Support for the experimental syntax 'jsx' isn't currently enabled
- Animating button MUI with Hover
- Module not found: Can't resolve 'react-pagination'
- React - Create multiple useRefs in one line using object or array
- How do I make sure my first render with React has a value from localStorage?
- Add dot notation to React.createElement
- React simply passing props to parent in class componenets
- Conditionally disabled React Checkboxes
- submit PDF file with formData in react
- react native and parse, currentuser is null after login and cmd+R
- react typescript return value with asynchronous functions
- Best approach to multilingual react webapp
- Test ClientPortal in Next.JS using Jest
- Live reload react app working with docker-compose
- react-bootstrap-modal not showing
- Array is not getting updated by useState
- How to check if a child element exists in parent in React?
- Passing websocket streaming data to child in reactJS
- Node app fails with SyntaxError: Unexpected token '...'