I'm new to React and l’m reading the documentation of react navigation
In this Section
const authContext = React.useMemo(
() => ({
signIn: async (data) => {
dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
},
signOut: () => dispatch({ type: 'SIGN_OUT' }),
signUp: async (data) => {
dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
},
}),
[]
);
I dont understand the purpose of using useMemo since we can do the same thing using UseEffect
is there any reason to use UseMemo over useEffect in this case ?
CodePudding user response:
The return value of useEffect is void. and the return value of useMemo is not void but memoized value. and it will calculate again if dependcy value changes. In your case, if useEffect is used
const authContext = React.useEffect(
() => (
setAuthContext({
signIn: async (data) => {
dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
},
signOut: () => dispatch({ type: 'SIGN_OUT' }),
signUp: async (data) => {
dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
},
})),[]);
Here need an additional state/variable (setAuthContext) to get the object. (Also causing rerender on state update)
CodePudding user response:
UseMemo is used to calculate a specific value and save that value in memory until one of the dependencies in the dependency array changes. For example, you have some dataset that has to undergo some operations based on other values, it will save the result until one or more of those values changes. This has essentially become just a normal value like an array, string, number, ...
UseEffect is something that runs every re-render and checks the dependency array. If any of the values within the dependency array changed the code within the useEffect will run. UseEffect doesn't save any results and is usually used to fetch async data and set some state within a useState. After this, you can have another useEffect execute some code when it sees that state updated and your app can continue execution.
Finally there's also useCallback that is similar to useMemo but is usually used to memoize functions. This will store the function in memory and essentially makes it a static function until anything within the dependency array changes.
Important to remember when using useMemo, useCallback or any other memoization is the fact that you're trading execution time for memory, so depending on the device your code runs on, and especially how much processing power/RAM it has you'll have to think about which functions benefit the most of using these features.
I definitely recommend just experimenting with these things and maybe reading/watching some more visual explanations about this topic since it also took me some time to get my head around when to use what.
I hope this helped!