React - Updated prop in custom hook - reactjs

I have a custom hook that gives me a certain percentage of the scroll. I takes the values from the state-management solution Zustand. I'm using it inside a component to update some styles on elements on the page.
The problem is that I only want to update these elements on a certain condition passed as prop of my component. And these conditions are not updated in my hook.
I don't know how I should change it in order to get the updated condition.
import create from 'zustand'
const useStore = create(() => {
scroll: 0
})
const useScroll = (callback: (scroll: number) => void): null => {
const subscribe = useRef()
useEffect(() => {
if (subscribe & subscribe.current) {
// Unsubscribe
subscribe.current()
}
subscribe.current = useStore.subscribe(() => {
callback(useStore.getState().scroll)
})
}, [subscribe])
return null
}
const myComponent = (condition: Boolean) => {
console.log(condition) // gives the updated value of the prop
useScroll(() => {
console.log(condition) // is not updated
})
}

My guess is that you need to add the callback parameter to the list of properties useEffect is watching:
useEffect(() => {
...
}, [subscribe, callback])
That way, whenever the function callback changes because of a new condition, the useEffect will re-run.

Related

Electron/React cannot access component state changes in ipcRenderer listener

I am using Electron with React and I am facing a little problem.
I am creating a functional component and in the useEffect hook I subscribe to ipcRenderer to listen for when ipcMain replies.
When ipcRenderer event triggers I am unable to access the latest state updates. All state variables values inside ipcRenderer.on function contain data when the component was initially created.
In the code below customers is an array state variable. If I console.log its value every time the ipcRenderer.on is fired it is always empty. I am absolutely sure this variable is not empty inside the component's context because it contains information that is rendered in a grid. When ipcRenderer.on is triggered my grid is reset or cleared. All I am trying to do is refresh a row in the grid when ipcRenderer.on is triggered.
useEffect(() => {
// Actions triggered in response to main process replies
ipcRenderer.on(IPCConstants.UPDATE_SALE_CUSTOMER, (event: any, arg: IUpdateResponse) => {
setIsLoading(false);
if(!arg.success) {
notifyError(arg.message);
return;
}
setCustomers(
customers.map(cst => {
if(cst.CUS_CustomerId === arg.customer.CUS_CustomerId){
cst.RowId = `${generateRandomValue()}`;
cst.isActive = arg.customer.isActive;
}
return cst;
})
)
});
return () => {
ipcRenderer.removeAllListeners(IPCConstants.UPDATE_SALE_CUSTOMER);
};
}, []);
useEffect(() => {
// Actions triggered in response to main process replies
ipcRenderer.on(IPCConstants.UPDATE_SALE_CUSTOMER, (event: any, arg: IUpdateResponse) => {
setIsLoading(false);
if(!arg.success) {
notifyError(arg.message);
return;
}
setCustomers(
customers.map(cst => {
if(cst.CUS_CustomerId === arg.customer.CUS_CustomerId){
cst.RowId = `${generateRandomValue()}`;
cst.isActive = arg.customer.isActive;
}
return cst;
})
)
});
return () => {
ipcRenderer.removeAllListeners(IPCConstants.UPDATE_SALE_CUSTOMER);
};
}, [customers, otherState (if needed)]); // <= whichever state is not up to date
You need to include the proper dependencies.
the useEffect will keep up to date with these state values
alternatively if you don't need the functionality of useState (unlikely) you can use useRef and the useEffect will always have the up to date ref without passing it as a dependency.

React useEffect to have different behavior on first load and subsequent updates

I am using React with typescript and I want to convert my class component to a functional component, but my class component has two different componentDidMount and comonentDidUpdate behaviors:
componentDidMount() {
this.props.turnResetOff();
}
componentDidUpdate() {
if (this.props.resetForm) {
this.resetChangeForm();
this.props.turnResetOff();
}
}
I just want my form to reset every time it loads except the first time, because I have a menu drop-down that allows clearing the form but I want the data to not reset on mount.
I tried using this: componentDidMount equivalent on a React function/Hooks component?
const turnResetOff = props.turnResetOff;// a function
const resetForm = props.resetForm;
const setPersonId = props.setPersonId;// a function
useEffect(() => {
turnResetOff();
}, [turnResetOff]);
useEffect(() => {
const resetChangeForm = () => {/*definition*/};
if (resetForm) {
resetChangeForm();
turnResetOff();
}
}, [resetForm, turnResetOff, setPersonId]);
However, this causes an infinite re-render. Even if I useCallback for turnResetOff:
turnResetOff={useCallback(() => {
if (shouldReset) {
setShouldReset(false);
}
}, [shouldReset])}
I also tried using useRef to count the number of times this has been rendered, with the same result (infinite rerender - this is a simplified version even).
const [shouldReset, setShouldReset] = useState<boolean>(false);
const mountedTrackerRef = useRef(false);
useEffect(() => {
if (mountedTrackerRef.current === false) {
console.log("mounted now!");
mountedTrackerRef.current = true;
// props.turnResetOff();
setShouldReset(false);
} else {
console.log("mounted already... updating");
// if (props.resetForm) {
if (shouldReset) {
// resetChangeForm();
// props.turnResetOff();
setShouldReset(false);
}
}
}, [mountedTrackerRef, shouldReset]);
When you call useEffect() you can return a clean-up function. That cleanup function gets called when the component is unmounted. So, perhaps what you want to do is this: when you are called with turnResetOff then call it, and return a function that calls turnResetOff. The return function will be called when the component unmounts, so next time the component mounts it won't reset.
Something to along these lines:
useEffect(
() => {
turnResetOff()
return () => {setShouldReset(false)}
}
,[turnResetOff, setShouldReset])
Using the logic you have in the class component, the fellowing should give you identical behavior in a functional component
const turnResetOff = props.turnResetOff;// a function
const resetForm = props.resetForm;
const setPersonId = props.setPersonId;// a function
// useEffect with an empty dependency array is identical to ComponentDidMount event
useEffect(() => {
turnResetOff();
}, []);
// Just need resetForm as dependency since only resetForm was checked in the componentDidUpdate
useEffect(() => {
const resetChangeForm = () => {/*definition*/};
if (resetForm) {
resetChangeForm();
turnResetOff();
}
}, [resetForm]);

React native screens not re-rendering when custom hook state got changed

I am using a custom hook in app purchases.
const useInAppPurchase = () => {
const context = useContext(AuthGlobal)
const [isFullAppPurchased, setIsFullAppPurchased] = useState(false)
useEffect(() => {
console.log(`InAppPurchase useEffect is called`)
getProductsIAP()
return async () => {
try {
await disconnectAsync()
} catch (error) {}
}
}, [])
....
}
When I used this hook at AccountScreen (where I do the purchase) Account screen is getting re-rendered once the payment is done.
i.e. isFullAppPurchased is changing from false -> true
const AccountScreen = (props) => {
const width = useWindowDimensions().width
const {
isFullAppPurchased,
} = useInAppPurchase()
return (
// value is true after the purchase
<Text>{isFullAppPurchased}</Text>
)
}
But I am using the same hook in CategoryList screen and after the payment is done when I navigate to the CategoryList screen, The values (isFullAppPurchased) is not updated (still false).
But when I do the re-rendering manually then I get isFullAppPurchased as true.
const CategoryList = (props) => {
const navigation = useNavigation()
const { isFullAppPurchased } = useInAppPurchase()
return (
// still value is false
<Text>{isFullAppPurchased}</Text>
)
}
What is the reason for this behaviour ? How should I re-render CategoryList screen once the payment is done ?
Thank you.
I see hook make API request only on mount, if whole parent component didn't unmount and rendered a new, value of hook stays same.
E.g. dependencies array is empty - [] so hook doesn't request data again.
Probably better idea is to pass isFullAppPurchased via context or redux from top level.
And put state and function to update that state in same place.

How to wait for multiple state updates in multiple hooks?

Example
In my scenario I have a sidebar with filters.. each filter is created by a hook:
const filters = {
customerNoFilter: useFilterForMultiCreatable(),
dateOfOrderFilter: useFilterForDate(),
requestedDevliveryDateFilter: useFilterForDate(),
deliveryCountryFilter: useFilterForCodeStable()
//.... these custom hooks are reused for like 10 more filters
}
Among other things the custom hooks return currently selected values, a reset() and handlers like onChange, onRemove. (So it's not just a simple useState hidden behind the custom hooks, just keep that in mind)
Basically the reset() functions looks like this:
I also implemented a function to clear all filters which is calling the reset() function for each filter:
const clearFilters = () => {
const filterValues = Object.values(filters);
for (const filter of filterValues) {
filter.reset();
}
};
The reset() function is triggering a state update (which is of course async) in each filter to reset all the selected filters.
// setSelected is the setter comming from the return value of a useState statement
const reset = () => setSelected(initialSelected);
Right after the resetting I want to do stuff with the reseted/updated values and NOT with the values before the state update, e.g. calling API with reseted filters:
clearFilters();
callAPI();
In this case the API is called with the old values (before the update in the reset())
So how can i wait for all filters to finish there state updated? Is my code just badly structured? Am i overseeing something?
For single state updates I could simply use useEffect but this would be really cumbersome when waiting for multiple state updates..
Please don't take the example to serious as I face this issue quite often in quite different scenarios..
So I came up with a solution by implementing a custom hook named useStateWithPromise:
import { SetStateAction, useEffect, useRef, useState } from "react";
export const useStateWithPromise = <T>(initialState: T):
[T, (stateAction: SetStateAction<T>) => Promise<T>] => {
const [state, setState] = useState(initialState);
const readyPromiseResolverRef = useRef<((currentState: T) => void) | null>(
null
);
useEffect(() => {
if (readyPromiseResolverRef.current) {
readyPromiseResolverRef.current(state);
readyPromiseResolverRef.current = null;
}
/**
* The ref dependency here is mandatory! Why?
* Because the useEffect would never be called if the new state value
* would be the same as the current one, thus the promise would never be resolved
*/
}, [readyPromiseResolverRef.current, state]);
const handleSetState = (stateAction: SetStateAction<T>) => {
setState(stateAction);
return new Promise(resolve => {
readyPromiseResolverRef.current = resolve;
}) as Promise<T>;
};
return [state, handleSetState];
};
This hook will allow to await state updates:
const [selected, setSelected] = useStateWithPromise<MyFilterType>();
// setSelected will now return a promise
const reset = () => setSelected(undefined);
const clearFilters = () => {
const promises = Object.values(filters).map(
filter => filter.reset()
);
return Promise.all(promises);
};
await clearFilters();
callAPI();
Yey, I can wait on state updates! Unfortunatly that's not all if callAPI() is relying on updated state values ..
const [filtersToApply, setFiltersToApply] = useState(/* ... */);
//...
const callAPI = () => {
// filtersToApply will still contain old state here, although clearFilters() was "awaited"
endpoint.getItems(filtersToApply);
}
This happens because the executed callAPI function after await clearFilters(); is is not rerendered thus it points to old state. But there is a trick which requires an additional useRef to force rerender after filters were cleared:
useEffect(() => {
if (filtersCleared) {
callAPI();
setFiltersCleared(false);
}
// eslint-disable-next-line
}, [filtersCleared]);
//...
const handleClearFiltersClick = async () => {
await orderFiltersContext.clearFilters();
setFiltersCleared(true);
};
This will ensure that callAPI was rerendered before it is executed.
That's it! IMHO a bit messy but it works.
If you want to read a bit more about this topic, feel free to checkout my blog post.

React: Trying to rewrite ComponentDidUpdate(prevProps) with react hook useEffect, but it fires when the app starts

I'm using a componentDidUpdate function
componentDidUpdate(prevProps){
if(prevProps.value !== this.props.users){
ipcRenderer.send('userList:store',this.props.users);
}
to this
const users = useSelector(state => state.reddit.users)
useEffect(() => {
console.log('users changed')
console.log({users})
}, [users]);
but it I get the message 'users changed' when I start the app. But the user state HAS NOT changed at all
Yep, that's how useEffect works. It runs after every render by default. If you supply an array as a second parameter, it will run on the first render, but then skip subsequent renders if the specified values have not changed. There is no built in way to skip the first render, since that's a pretty rare case.
If you need the code to have no effect on the very first render, you're going to need to do some extra work. You can use useRef to create a mutable variable, and change it to indicate once the first render is complete. For example:
const isFirstRender = useRef(true);
const users = useSelector(state => state.reddit.users);
useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
} else {
console.log('users changed')
console.log({users})
}
}, [users]);
If you find yourself doing this a lot, you could create a custom hook so you can reuse it easier. Something like this:
const useUpdateEffect = (callback, dependencies) => {
const isFirstRender = useRef(true);
useEffect(() => {
if (isFirstRender.current) {
isFirstRender.current = false;
} else {
return callback();
}
}, dependencies);
}
// to be used like:
const users = useSelector(state => state.reddit.users);
useUpdateEffect(() => {
console.log('users changed')
console.log({users})
}, [users]);
If you’re familiar with React class lifecycle methods, you can think
of useEffect Hook as componentDidMount, componentDidUpdate, and
componentWillUnmount combined.
As from: Using the Effect Hook
This, it will be invoked as the component is painted in your DOM, which is likely to be closer to componentDidMount.

Resources