score:343
the pattern that you need to follow depends on your use case.
first: you might have a situation where you need to add event listener during the initial mount and clean them up at unmount and another case where a particular listener needs to be cleaned up and re-added on a prop change.
in such a case, using two different useeffect
is better to keep the relevant logic together as well as having performance benefits
useeffect(() => {
// adding event listeners on mount here
return () => {
// cleaning up the listeners here
}
}, []);
useeffect(() => {
// adding listeners everytime props.x changes
return () => {
// removing the listener when props.x changes
}
}, [props.x])
second: you need to trigger an api call or some other side-effect when any of the state or props change from a defined set. in such a case a single useeffect
with the relevant dependencies to monitor would be better
useeffect(() => {
// side effect here on change of any of props.x or statey
}, [props.x, statey])
third: you need separate side-effect for different sets of changes. in such a case, separate out relevant side-effects into different useeffect
s
useeffect(() => {
// some side-effect on change of props.x
}, [props.x])
useeffect(() => {
// another side-effect on change of statex or statey
}, [statex, statey])
score:13
it's perfectly fine to have have multiple useeffect.
here's how one of my setups looks like:
/*
* backend tags list have changed add the changes if needed
*/
useeffect(() => {
settagslist(settagsadded);
}, [settagsadded]);
/*
* backend files have changed add the changes if needed
*/
useeffect(() => {
for (let i = 0; i < changedfilesmeta.length; i += 1) {
// is the list item value changed
if (changedfilesmeta[i].id === currenteditablefile.id) {
unstable_batchedupdates(() => {
settags(changedfilesmeta[i].tags ? changedfilesmeta[i].tags : []);
});
}
}
}, [changedfilesmeta]);
/*
* reset when user select new files using the filepicker
*/
useeffect(() => {
if (setnewfiles.length > 0) {
unstable_batchedupdates(() => {
setcurrentfile(null);
setdescription('');
settitle('');
settags([]);
});
}
}, [setnewfiles]);
/*
* user selecet to edit a file, change to that file
*/
useeffect(() => {
// when user select a file to edit it
if (currenteditablefile && currenteditablefile !== thecurrentfile) {
setcurrentfile(currenteditablefile);
unstable_batchedupdates(() => {
setdescription(currenteditablefile.description);
settitle(currenteditablefile.title);
settags(currenteditablefile.tags);
});
}
}, [currenteditablefile]);
score:82
you should use multiple effects to separate concerns as suggested by reactjs.org.
Source: stackoverflow.com
Related Query
- In general is it better to use one or many useEffect hooks in a single component?
- Which is more efficient: use of many useState hooks or one useState for often updated object?
- how to use one component render many html fragment in reactjs?
- How to use multiple graphql query hooks in single function component in react?
- In React, how do I properly use hooks to update one component when I trigger an Add function in another component?
- Cant use Hooks with my React Component Library. Invariant Violation: Invalid hook call
- How do I use React hooks in my component library?
- how to use AppState in a functional component and hooks? Necessary or am I using useEffect incorrectly?
- Which one has better performance: add and remove event listener on every render VS running an useEffect to update a ref
- How to use useEffect hook properly with array dependency. I passed state from redux store and still my component renders infinitely
- How can I use one component (page) for multiple route in Next JS
- How can one use a polymer component inside a react component ? Is it possible?
- Invalid hook call. Hooks can only be called inside of the body of a function component when i call useQuery in useEffect
- React - how to use hooks to hide or show a component based on an onChange event
- How to use Redux store in one component without Provider but with connect, because children aren't necessary?
- React useEffect calls API too many time, How can I limit the API call to only once when my component renders?
- How to use setTimeout() along with React Hooks useEffect and setState?
- React hooks rendering component before useEffect finishes
- How can I use useEffect in React to run some code only when the component first mounts, and some other code whenever an event occurs (repeatedly)?
- how to import multiple components as a single component and use them in lazy load
- Difference and use cases with useEffect and useMemo hooks on React
- How to use Apollo/Graphql hooks within external React.js component library
- Is it possible to use hooks on a single property of a context?
- How to refactor a react component that is handling too many conditions / use cases?
- Is it possible to use React Hooks in class component by using HOC(Higher Order Component)?
- How to use multiple or two state values in one component or class file in react JS?
- How to use date-picker in a react component using hooks
- Use multiple 'useContext' in one React component
- Reactjs - translating a class component to a functional one with hooks
- convert from React component to using one hooks
More Query from same tag
- Pass parameter to component is readonly ReactJs
- How to render two different arrays data into a single array of objects?
- Why there is no transition from `green` to `blue`?
- esri-leaflet-geosearch: how to integrate it with React
- Interupt code and wait for user interaction in a loop - React
- ReactJs - Loading cross domain assets
- Changing state on route change in React
- Warning: React has detected a change in the order of Hooks called by Table
- Unexpected character '' when importing a JSX file into a JS file in React
- react-scripts build ignores conditional css imports
- How to loop thorough object and create child component in React.js
- How to change heading tag upon button click using React?
- React state vs props for complex structure
- How to change the default text of the file input with reactjs?
- React how can I build minify code in react library
- How to redirect from component after action was called successfully in React?
- Function setIntervall become faster after change router
- Cannot read property 'setState' of undefined when property is defined
- how to perform a proper redirect in reactjs(16.13.0) code for a custom material ui component?
- How to correctly map over a React element with separate radio button form elements?
- Change MongoDB natural order, generate _id manually and sort by _id, insert rows between two rows implementation (React Data Grid )
- How can I update state once onPress via TouchableOpacity in React Native?
- setState not a function after binding this
- How to distinguish admin and customer role when create user with createUserWithEmailAndPassword firebase auth in ReactJS
- How to clear the preview image in form on submit but display it in the web page without any problem in React?
- HTML BootStrap Navbar not displaying as expected
- React Router / Hapi Server Side Rendering Error
- React Ant Design - How to set Table to 100% height
- How to zoom.in() in a button (React swiper)?
- BufferedConsole module not found