1676402520
In this React tutorial, we learn about What Is The UseMemo Hook and How Does It Work?. Performance is important, especially in large-scale application. The React useMemo hook is one tool you can use to improve the performance of your React apps. This tutorial will help you understand what useMemo hook is and how it works. It will also show you how to use it.
The React useMemo hook is one of the additional hooks that are implemented in React. All these hooks serve different purposes. The purpose of useMemo hook is to memoize the output of a function. What this means is that it executes some function and remember the output of that function.
The important part comes when your component re-renders. After re-render, any function in the component would be normally created. If you are also calling the function, it would be also executed again. The useMemo hook helps you avoid this. It allows you to execute the memoized function only under specific conditions.
When these conditions are not met, the useMemo will not execute the function. Instead, it will return the value from the last execution. This simple thing can help you optimize your React application by avoiding expensive calculations every time one of your components re-render.
When you think about it, the useMemo hook is a bit like the useCallback hook. Both use memoization. The main, and maybe only, difference between these two, is that while useCallback hook helps you memoize whole function, the useMemo helps you memoize only the output of functions.
The React useMemo hook accepts two parameters. These parameters are: some function whose output you want to memoize and array of dependencies. The useMemo hook will execute the function you passed as an argument after the initial render by default.
// Import useMemo hook from React:
import { useMemo } from 'react'
export default function App() {
// useMemo syntax example:
const memoizedVal = useMemo(() => {/* Some function */}, [/* Dependencies */])
return (
<div className="App"></div>
)
}
When the useMemo hook runs, and executes the function you passed, is determined by the second argument the hook accepts, the dependency array. By changing this argument you change when the hook runs. There are currently three options.
The first option is to run the hook only after the initial render and never again. Then, when something causes the component to re-render, useMemo will not execute the function again. Instead, it will return the memoized output of the function. It will do this for every subsequent re-render.
If this is what you want, you have to specify the dependency array as empty. This means that there are no values the useMemo hook should watch. It should always return the memoized output.
// Import useMemo hook from React:
import { useEffect, useMemo, useState } from 'react'
export default function App() {
// Create state for count:
const [count, setCount] = useState(1)
// Create computationally expensive function:
const fibonacci = (num) => {
return num === 2 ? 1 : num === 1 ? 0 : fibonacci(num - 1) + fibonacci(num - 2)
}
// Memoize fibonacci function:
const memoizedVal = useMemo(() => fibonacci(count), [])
// Above, the dependency array is empty. The useMemo will run only once.
// Check if memoizedVal changes
useEffect(() => {
// This log will show only once because
// useMemo will run only once.
console.log(memoizedVal)
}, [memoizedVal])
return (
<div className="App">
<p>{count}</p>
<button onClick={() => setCount(prevCount => prevCount += 1)}>Increase count</button>
</div>
)
}
The example above demonstrates that useMemo runs only after initial render. It will generate fibonacci number for the initial value of count
state. When you increase the count, by clicking the button, value of count
will increase. You can see this change in the paragraph above the button.
However, no log will show up. This is because the useMemo hook will not run the fibonacci function again. It will return the same value you got after the initial render. Since the value of memoizedVal
is the same, the useEffect hook will not execute the console.log()
. Remember, it watches only the memoizedVal
.
The second option is to run useMemo, and execute the function you passed, again when specific value changes. This will be useful when the function you passed as an argument accepts some value from the outside. When this outside value changes you may want to re-calculate the output so the output is correct.
To do this, you have to specify the value you want to “watch” as one of the dependencies. useMemo will then watch this value and execute the function you passed every time the watched value changes. If it doesn’t change, useMemo will return the memoized value, value from the last execution.
There is no limit to how many dependencies you can specify for the useMemo hook. If you want the hook to watch one, specify one. If you want it to watch 10, specify all ten. Just make sure to specify all dependencies you need and omit those you don’t need. Otherwise, useMemo will re-execute the function too often or not often enough.
// Import useMemo hook from React:
import { useEffect, useMemo, useState } from 'react'
export default function App() {
// Create state for count:
const [count, setCount] = useState(1)
// Create computationally expensive function:
const fibonacci = (num) => {
return num === 2 ? 1 : num === 1 ? 0 : fibonacci(num - 1) + fibonacci(num - 2)
}
// Memoize fibonacci function:
const memoizedVal = useMemo(() => fibonacci(count), [count])
// Above, the "count" is specified as a dependency. When the value of "count" changes useMemo will run and execute fibonacci function.
// Check if memoizedVal changes
useEffect(() => {
console.log(memoizedVal)
}, [memoizedVal])
return (
<div className="App">
<p>{count}</p>
<button onClick={() => setCount(prevCount => prevCount += 1)}>Increase count</button>
</div>
)
}
In the second example, the useMemo watches the count
value because it is specified as a dependency. Because of this, useMemo runs every time the count
value changes and executes the fibonacci function. Every change of count
also changes the input of the fibonacci function and also the output it returns.
Since execution of fibonacci function changes the memoizedVal
, this also causes the useEffect hook to execute the console.log
. As a result, new message with new value shows up in the console.
The last option is to tell useMemo to re-run the function you passed on every re-render. This is kind of a nonsense. There is no reason to use useMemo to memoize something just to actually never memoize it. However, since this is possible, it is still an option. Warning: don’t do this. It is dumb and waste of time.
Anyway… Let’s say you are in a situation where this is the only option, which is incredibly unlikely to happen. In order to convince the useMemo hook to run on every render you have to omit the dependency array. Pass in only one argument, the function.
// Import useMemo hook from React:
import { useEffect, useMemo, useState } from 'react'
export default function App() {
// Create state for count:
const [count, setCount] = useState(1)
// Create computationally expensive function:
const fibonacci = (num) => {
return num === 2 ? 1 : num === 1 ? 0 : fibonacci(num - 1) + fibonacci(num - 2)
}
// Memoize fibonacci function:
const memoizedVal = useMemo(() => fibonacci(count))
// Above, no dependency array is specified. This will cause the useMemo to execute fibonacci function on every render.
// Check if memoizedVal changes
useEffect(() => {
console.log(memoizedVal)
}, [memoizedVal])
return (
<div className="App">
<p>{count}</p>
<button onClick={() => setCount(prevCount => prevCount += 1)}>Increase count</button>
</div>
)
}
In the last example, we removed the dependency array argument from the useMemo hook. The useMemo hook now watches basically everything that happens. When something happens, that will cause re-render, useMemo will also execute the fibonacci function. This will, in turn, change the memoizedVal
.
This change will tell useEffect to execute the console.log
. As a result, a new value of memoizedVal
will show up in the console. To reiterate, don’t do this. It doesn’t make sense to use useMemo and then never let it memoize anything.
Performance is important and it is easy to go over the edge when trying to optimizer everything. It is just as easy to over-use the React useMemo hook. Think before you decide to use useMemo hook. Remember that the hook itself introduces some overhead. The hook brings in new complex logic you have to take into account.
It can also create new performance issues, issue you didn’t have before. When you memoize something, you store it in the memory. This gives more space for the CPU. However, there are still resources that are consumed. The only thing that changed is the type of resource it consumes.
So, use useMemo only for really expensive computations. Make sure you use that memory for things that can make a difference. Use profiling tools to identify those expensive computations, computations that use a lot of resources. Try to optimize these with useMemo and see if the profile changes for the better.
Additional warning. Don’t rely on useMemo too much. As is mentioned in the React docs, useMemo doesn’t guarantee you to execute the function only when dependencies change. React may also choose to remove memoized values and recalculate them so it can free up memory. So, make sure your code works without useMemo as well.
One more thing. Don’t use functions you passed to useMemo hook to create side-effects. Side-effects should be made inside the useEffect hook. Also, don’t use useMemo to update state values. This is also a side-effect, but it is important to mention it. Use useMemo only for what it is intended, to memoize output values.
The React useMemo hook can be useful when you look for ways to improve performance of your React applications. It can help you optimize expensive computations by memoizing output of these computations and re-run them only when necessary. I hope that this tutorial helped you understand what the useMemo hook is, how it works and also how to use it.
Original article sourced at: https://blog.alexdevero.com
1668581044
The useMemo()
hook is one of many built-in React hooks that you can use inside your function components.
This hook is designed to improve the performance of your React component through the use of memoization technique (you can also say memorizing, but the right technical term is memoizing)
Memoization is an optimization technique where the result of an expensive function call is stored in memory. The computer did this by “remembering” the input that it received, connecting the input with the result.
For example, let’s say you have a function add()
that adds up two numbers passed as its arguments:
const num = add(1, 1);
// num = 2
Using the memoization technique, you can memoize the result of calling the add()
function. The next time the function is called, the computer would first look at the arguments you passed to the function.
When the computer sees that you are passing the same arguments as the previous call – which is (1, 1)
in the case above – then it will return the value 2
stored in the memory and skips running the function.
The useMemo()
hook is used to apply the memoization technique to the function that you passed as its argument.
Using the add()
function as an example, the hook syntax is as follows:
const firstNumber = 1;
const secondNumber = 1;
const num = useMemo(() => {
add(firstNumber, secondNumber);
}, [firstNumber, secondNumber]);
In the above example, the useMemo()
hook accepts two arguments:
callback
function that will run the function to be memoizedarray
that will be observed by the hookAs long as the values inside the dependency array
don’t change, then the memoized function add()
won’t be called and the memoized result will be returned by the hook.
To test a memoized function, you can add a console.log()
statement inside it. When the value is retrieved from memory, the log won’t be printed.
In the following <App>
component, the expensive()
function is called every time you clicked on the <button>
even though the props are the same:
function App() {
const [toogle, setToogle] = useState(false);
return (
<>
<ChildComponent num={1} />
<button onClick={() => setToogle(!toogle)}>{toogle.toString()}</button>
</>
);
}
function ChildComponent(props) {
const { num } = props;
const expensive = () => {
console.log("running expensive function!");
return num + num;
};
return <h1>{expensive()}</h1>;
}
Using the useMemo()
hook, you can skip the expensive()
function call as in the example below:
function ChildComponent(props) {
const { num } = props;
const expensive = (num) => {
console.log("running expensive function!");
return num + num;
};
const result = useMemo(() => expensive(num), [num]);
return <h1>{result}</h1>;
}
The <ChildComponent>
above will only call the expensive()
function once during the initial render and will return the value stored in memory for subsequent calls.
The dependencies of the useMemo()
hook usually comes from props passed by the parent component, which means as long as the props passed to the component remains the same, the memoized function will be skipped.
Since the useMemo()
hook is designed for optimization, you need to make sure that you are only applying the hook when you have expensive function calls inside your project.
Memoization should only be used when you have a component with an expensive function call that could re-render when the parent component has its props changed.
One example where useMemo()
hook might be useful is when you have a social media application with switchable light or dark themes and an expensive search function call.
The code pattern would look like the example below:
function App() {
const [theme, setTheme] = useState("light");
const [username, setUsername] = useState("");
const changeTheme = () => {
const newTheme = theme === "light" ? "dark" : "light";
setTheme(newTheme);
};
return (
<>
<input
type="text"
placeholder="Search Users"
onChange={(e) => setUsername(e.target.value)}
/>
<SearchResult username={username} />
<button onClick={() => changeTheme}>{theme}</button>
</>
);
}
function SearchResult({username}) {
const expensiveSearch = (username) => {
// perform search and return results
}
return <h1>Search result placeholder</h1>
}
You can memoize the result of that expensiveSearch()
call using the useMemo()
hook so that if the user changes the theme
after performing a search, the same search result is displayed from memory instead of calling the search function again.
And that will be all about the useMemo()
hook 😉
Original article source at: https://sebhastian.com/
1614329473
G Suite is one of the Google products, developed form of Google Apps. It is a single platform to hold cloud computing, collaboration tools, productivity, software, and products. While using it, many a time, it’s not working, and users have a question– How to fix G Suite not working on iPhone? It can be resolved easily by restarting the device, and if unable to do so, you can reach our specialists whenever you want.
For more details: https://contactforhelp.com/blog/how-to-fix-the-g-suite-email-not-working-issue/
#g suite email not working #g suite email not working on iphone #g suite email not working on android #suite email not working on windows 10 #g suite email not working on mac #g suite email not syncing
1607930471
Xfinity, the tradename of Comcast Cable Communications, LLC, is the first rate supplier of Internet, satellite TV, phone, and remote administrations in the United States. Presented in 2010, previously these administrations were given under the Comcast brand umbrella. Xfinity makes a universe of mind boggling amusement and innovation benefits that joins a great many individuals to the encounters and minutes that issue them the most. Since Xfinity is the greatest supplier of link administrations and home Internet in the United States, it isn’t amazing that the organization gets a ton of investigating and inquiry goal demands on its telephone based Xfinity Customer Service.
#my internet is not working comcast #comcast tv remote not working #my xfinity internet is not working #xfinity stream not working #xfinity wifi hotspot not working
1607768450
In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/
#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks
1616058467
Comcast is one of the email service providers and you can log-in by using credentials such as username and password. However, while using it, many users face Comcast email, not working problems. Here we discussed How To Resolve Xfinity Comcast Email Not Working Problems easily by going through the steps. This article helps you to get rid of several issues associated with Xfinity Comcast Email Not Working Issues.
Many of them might be first-time users of Comcast. While you have created an account, you may not know the procedure for sign-in but while log-in some users face the issue and unable to get into your account. The log-in procedure to the account is very simple and easy to follow. Let’s start with the procedure to follow the below steps.
**Steps To Resolve Xfinity Comcast Email Login Problem
**
After going, through these steps, you can surely get the issue resolved related to Xfinity Comcast Email Not Working Problems and if you require technical assistance related to it, then you can feel free to get in touch with our Xfinity Comcast Email specialists at +1-888-857-5157. Our support team available 24*7 to help resolve your issues related to Xfinity Comcast Email Problems.
#resolve xfinity comcast email not working problems #xfinity comcast email not working issues #xfinity comcast email not working problems #xfinity comcast email not working #xfinity comcast email