When should you use evergreen versus topical content?
When evaluating the time-sensitivity of the content that you create, there are two major categories. Content will either be topical or evergreen. You should always include both categories in your marketing strategy, as each has its ideal purpose.
At the most basic level, evergreen content is relevant for a long time while topical content has a shorter period of relevancy. To better understand their uses, however, you must take a closer look at their differences.
What is evergreen content?
As mentioned, evergreen content is distinguished by the fact that it stays relevant even after significant time has passed following its publication.
Two common examples of evergreen content are instructional content, such as how to make a blog post, and listicles, such as the top five companies in a given category. Other examples include product reviews, tips, and certain types of videos. A great example of an evergreen listicle would be this article on Travel Wanderlust that talks about the 10 best amusement parks in the world.
An evergreen blog post or article can answer frequently asked questions. It could provide advice and explanations. Or it could explain industry concepts that some readers may have trouble understanding.
Designed to drive traffic continually
Because evergreen content is designed to be relevant for a long time, it should ideally drive traffic to your website continually over that extended period. Its existence will also boost your search engine rankings, further positioning your company as an authority in the industry. To reap those particular benefits, you will need to incorporate the correct keywords into your evergreen content and optimise for SEO.
Our post about free online writing courses still generates traffic for us every single month and is ranked high on page one for relevant search terms.
It still needs to be updated
Just because evergreen content should last for a long time, that does not mean that you get to create it and leave it alone. You will still need to review the articles regularly in the future to ensure all information is up-to-date. Make updates to the articles in the future, with the update date listed, if necessary.
You can repurpose it
Because the information contained in evergreen content is relevant for a long period, you can also easily repurpose it in the future. For example, you could combine multiple evergreen blog posts on similar topics into an evergreen long-form guide.
What is topical content?
We have already established that topical content is more time-sensitive and is mostly relevant just at the given moment.
Newsjacking, the term for writing about popular news stories, is a common example of topical content. Another example is stories about current trends, such as those in fashion or your industry. Other examples of topical content include those that focus on upcoming events, like New Year’s, the Olympics, or annual reports. Statistics are another good example of topical content since they are unlikely to be relevant for long.
The goal with your topical content is to gain a spike in views on your website. You want the content to have a large number of views at first, while it is still relevant. You expect this to taper off soon, at which point you will create another spike with a new piece of topical content.
Why you need both
It is common to wonder why you need both evergreen and topical content. After all, why is topical content necessary if evergreen content lasts? There are actually a few important reasons for this. One of them is that spike in views that topical content should create. Regularly publishing topical content leads to consistent spikes, benefiting your brand and boosting your potential leads.
Additionally, by utilising both strategies together, you can show that your brand is a thought leader. You can show those who visit your website that you are knowledgeable about the elements of the industry that will never change, such as how to complete relevant tasks. You also show that you remain up-to-date with relevant industry advances and events. Clients always want to work with companies that are aware of the latest methods and products, as these tend to lead to the best results.
Scrollbars are natural progress meters. How far the scrollbar is down or across is how much progress has been made scrolling through that element (often the entire page). But, they are more like progress indicators than meters, if you think of a meter as something that “fills up” as you go.
We can use some CSS trickery to make the scrollbar fill up as we go.
This will only work with -webkit- vendor-prefixed scrollbar-styling properties. In other words, these are non-standard. The standardized scrollbar styling properties are scrollbar-width and scrollbar-color, which can’t pull this kind of thing off, but are probably a safer bet in the long run. Still, the vendor-prefixed versions probably aren’t going anywhere, so if you consider this a weird form of progressive enhancement, that’s probably fine.
What’s the trick?
Essentially, it’s hanging a huge box-shadow off the top of the scrollbar thumb — or off the side if it’s a horizontally scrolling element.
That example didn’t differentiate the thumb part of the scrollbar at all, which makes it more meter-like, but also harder to use. My demo has a slightly different color thumb.
Can I really use this?
No! Aside from it being super weird and non-standard. Safari flips it’s lid and I have no idea how to fix it.
There was a discussion recently on the Animation at Work Slack: how could you make a CSS motion path responsive? What techniques would be work? This got me thinking.
A CSS motion path allows us to animate elements along custom user-defined paths. Those paths follow the same structure as SVG paths. We define a path for an element using offset-path.
These values appear relative at first and they would be if we were using SVG. But, when used in an offset-path, they behave like px units. This is exactly the problem. Pixel units aren’t really responsive. This path won’t flex as the element it is in gets smaller or larger. Let’s figure this out.
To set the stage, the offset-distance property dictates where an element should be on that path:
CodePen Embed Fallback
Not only can we define the distance an element is along a path, but we can also define an element’s rotation with offset-rotate. The default value is auto which results in our element following the path. Check out the property’s almanac article for more values.
CodePen Embed Fallback
To animate an element along the path, we animate the offset-distance:
CodePen Embed Fallback
OK, that catches up to speed on moving elements along a path. Now we have to answer…
Can we make responsive paths?
The sticking point with CSS motion paths is the hardcoded nature. It’s not flexible. We are stuck hardcoding paths for particular dimensions and viewport sizes. A path that animates an element 600px, will animate that element 600px regardless of whether the viewport is 300px or 3440px wide.
This differs from what we are familiar with when using SVG paths. They will scale with the size of the SVG viewbox.
Try resizing this next demo below and you’ll see:
The SVG will scale with the viewport size as will the contained path.
The offset-path does not scale and the element goes off course.
CodePen Embed Fallback
This could be okay for simpler paths. But once our paths become more complicated, it will be hard to maintain. Especially if we wish to use paths we’ve created in vector drawing applications.
For example, consider the path we worked with earlier:
To scale that up to a different container size, we would need to work out the path ourselves, then apply that path at different breakpoints. But even with this “simple” path, is it a case of multiplying all the path values? Will that give us the right scaling?
A more complex path such as one drawn in a vector application is going to be trickier to maintain. It will need the developer to open the application, rescale the path, export it, and integrate it with the CSS. This will need to happen for all container size variations. It’s not the worst solution, but it does require a level of maintenance that we might not want to get ourselves into.
It feels like a JavaScript solution makes sense here. GreenSock is my first thought because its MotionPath plugin can scale SVG paths. But what if we want to animate outside of an SVG? Could we write a function that scales the paths for us? We could but it won’t be straightforward.
Trying different approaches
What tool allows us to define a path in some way without the mental overhead? A charting library! Something like D3.js allows us to pass in a set of coordinates and receive a generated path string. We can tailor that string to our needs with different curves, sizing, etc.
With a little tinkering, we can create a function that scales a path based on a defined coordinate system:
CodePen Embed Fallback
This definitely works, but it’s also less than ideal because it’s unlikely we are going to be declaring SVG paths using sets of coordinates. What we want to do is take a path straight out of a vector drawing application, optimize it, and drop it on a page. That way, we can invoke some JavaScript function and let that do the heavy lifting.
So that’s exactly what we are going to do.
First, we need to create a path. This one was thrown together quickly in Inkscape. Other vector drawing tools are available.
Next, let’s optimize the SVG. After saving the SVG file, we’ll run it through Jake Archibald’s brilliant SVGOMG tool. That gives us something along these lines:
Now we can create a JavaScript function to handle the rest. Earlier, we created a function that takes a set of data points and converts them into a scalable SVG path. But now we want to take that a step further and take the path string and work out the data set. This way our users never have to worry about trying to convert their paths into data sets.
There is one caveat to our function: Besides the path string, we also need some bounds by which to scale the path against. These bounds are likely to be the third and fourth values of the viewBox attribute in our optimized SVG.
We won’t go through this function line-by-line. You can check it out in the demo! But we will highlight the important steps that make this possible.
First, we’re converting a path string into a data set
The biggest part of making this possible is being able to read the path segments. This is totally possible, thanks to the SVGGeometryElement API. We start by creating an SVG element with a path and assigning the path string to its d attribute.
// To convert the path data to points, we need an SVG path element.
const svgContainer = document.createElement('div');
// To create one though, a quick way is to use innerHTML
svgContainer.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg">
<path d="${path}" stroke-width="${strokeWidth}"/>
</svg>`;
const pathElement = svgContainer.querySelector('path');
Then we can use the SVGGeometryElement API on that path element. All we need to do is iterate over the total length of the path and return the point at each length of the path.
convertPathToData = path => {
// To convert the path data to points, we need an SVG path element.
const svgContainer = document.createElement('div');
// To create one though, a quick way is to use innerHTML
svgContainer.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg">
<path d="${path}"/>
</svg>`;
const pathElement = svgContainer.querySelector('path');
// Now to gather up the path points.
const DATA = [];
// Iterate over the total length of the path pushing the x and y into
// a data set for d3 to handle 👍
for (let p = 0; p < pathElement.getTotalLength(); p++) {
const { x, y } = pathElement.getPointAtLength(p);
DATA.push([x, y]);
}
return DATA;
}
Next, we generate scaling ratios
Remember how we said we’d need some bounds likely defined by the viewBox? This is why. We need some way to calculate a ratio of the motion path against its container. This ratio will be equal to that of the path against the SVG viewBox. We will then use these with D3.js scales.
We have two functions: one to grab the largest x and y values, and another to calculate the ratios in relation to the viewBox.
The last piece of the puzzle is to actually generate the path for our element. This is where D3.js actually comes into play. Don’t worry if you haven’t used it before because we’re only using a couple of functions from it. Specifically, we are going to use D3 to generate a path string with the data set we generated earlier.
To create a line with our data set, we do this:
d3.line()(data); // M10.362000465393066,18.996000289916992L10.107386589050293, etc.
The issue is that those points aren’t scaled to our container. The cool thing with D3 is that it provides the ability to create scales. These act as interpolation functions. See where this is going? We can write one set of coordinates and then have D3 recalculate the path. We can do this based on our container size using the ratios we generated.
For example, here’s the scale for our x coordinates:
The domain is from 0 to our highest x value. The range in most cases will go from 0 to container width multiplied by our width ratio.
There are times where our range may differ and we need to scale it. This is when the aspect ratio of our container doesn’t match that of our path. For example, consider a path in an SVG with a viewBox of 0 0 100 200. That’s an aspect ratio of 1:2. But if we then draw this in a container that has a height and width of 20vmin, the aspect ratio of the container is 1:1. We need to pad the width range to keep the path centered and maintain the aspect ratio.
What we can do in these cases is calculate an offset so that our path will still be centered in our container.
This demo (viewed best in full screen) shows three versions of the element using a motion path. The paths are present to easier see the scaling. The first version is the unscaled SVG. The second is a scaling container illustrating how the path doesn’t scale. The third is using our JavaScript solution to scale the path.
CodePen Embed Fallback
Phew, we did it!
This was a really cool challenge and I definitely learned a bunch from it! Here’s a couple of demos using the solution.
CodePen Embed Fallback
CodePen Embed Fallback
It should work as a proof of concept and looks promising! Feel free to drop your own optimized SVG files into this demo to try them out! — it should catch most aspect ratios.
CodePen Embed Fallback
I’ve created a package named “Meanderer” on GitHub and npm. You can also pull it down with unpkg CDN to play with it in CodePen, if you want to try it out.
I look forward to seeing where this might go and hope we might see some native way of handling this in the future. ?
Procreate is one of the most popular digital illustration apps that creative designers find quite unique owing to its excellent features and free & premium brushes that are sufficient for every need. Improving your drawing experience and staying on top of professional design is made possible with sophisticated features of Procreate.
Even though working on complex illustrations with Procreate might not be ideal, it is excellent for digital sketching, drawing and painting with its powerful layers and countless brushes. Procreate brush and tool presets promise that you’ll end up with drastically improved results. Along with a great deal of ready-to-use free Procreate brushes, you can also create custom brushes and share them with other users.
Regardless of what you are using Procreate for, Procreate brushes make sure you get the best experience of this sketching app. Finding the best Procreate brushes and expanding your selection of brushes might take some time yet still it would be the quickest way if you are looking for some inspiration and a brand new perception.
In addition to numerous Procreate brushes that you can find online, we have also picked the best free & Premium Procreate brushes created by individual designers. Every stroke and style promises a brand new touch to your designs with this curated selection of brushes.
We’ve got you covered! Be sure to check out our top picks to find the perfect additions to include in your own collection. All you need is to keep your iPad handy and get access to the App Store then you can begin to work on your next masterpiece.
Best Free and Premium Procreate Brushes for the iPad Pro
Adding new brushes to your Procreate brush collection will definitely help you master your artistic and creative abilities while designing your next work of art. You will notice the special touch, personality, and depth that come along with combining a few of these brushes to make your art unique.
On a final note, if you’re not using an iPad Pro you can also check out our articles, Procreate for Android and Procreate for Windows which also offer a versatile collection of brushes to create complex works of art.
It’s the oldest way to market your product. But has it also become old-fashioned?
In this age of social media marketing and chatbots, the debate has heated up on the relevance of email marketing. And yet, marketers continue to use it and swear by its benefits.
So, should you include email marketing in your marketing strategy or not?
And if you do, which plugin or service do you use?
We’re going to answer both questions for you in this article.
First, we’ll take a look at 5 reasons why email marketing is still relevant for any WordPress website, and then we’ll introduce you to some popular email marketing plugins and services that are available for WordPress. So without taking any more time, lets jump straight into it:
Reasons why Email Marketing is important for your WordPress website
First of all, email marketing is more effective than social media marketing from a conversion perspective.
Why? Because your social media posts might be missed by a lot of your fans and followers. What if someone doesn’t open up Facebook that day?
But when you send out an email it reaches every single subscriber.
So the reach is way higher than any of the social media platforms. When the reach is higher, the traffic you get is also higher.
Don’t get me wrong – social media marketing is important to generate new leads in any modern marketing strategy, but if you want to convert those leads into customers and repeat customers then email marketing is the way to go.
2. It makes you independent
The second good thing about email marketing is that it makes you independent.
With Social Media marketing you depend on the rules of Facebook and Twitter, while in search engine marketing you depend on Google. If any of these companies change their algorithms (which they often do), your traffic takes a beating.
However, with email marketing, there is no such problem. Once you’ve built a list of subscribers, it’s completely up to you to use it any way you please.
3. It’s cost-effective
Email marketing is very cost-effective when compared to any other method of marketing. Once you’ve built a sizable list of email subscribers, you can share your content with them without spending a ton of time and money.
All you need to do is invest in a good email marketing automation plugin, and that’s all. Depending on the resources available in your organization you may also need to hire someone to create the content for email marketing, but still, your total money spent on it will be much less while your ROI is much higher than other marketing channels.
4. It’s customizable
Email marketing is also customizable. You can generate a variety of email lists from your site by serving different types of content to different audiences. Then each of those lists can be targeted with the help of customized emails and content to maximize the results.
For instance, if you run an e-commerce site, your customers can subscribe to updates about a product that has sold out. Then as soon as the product is back in stock, they can be notified of it automatically. Similarly, if you sell downloadable products (i.e. online course, ebook, etc.) then you can build separate lists for your free and paid subscribers, providing them access to different types of content.
5. It’s measurable
Finally, email marketing is also highly measurable. You can track the results of every single campaign that you run with email marketing and every single event that took place with your emails.
From the opening of mails to bounce rate to unsubscribe rate to links clicked, everything can be tracked with complete accuracy. You can also perform split tests or A/B tests on your emails, and their results can also be measured. There’s no guesswork involved, which helps you in optimizing your marketing campaigns effectively.
Best Email marketing plugins
We just told you 5 of the many reasons why email marketing is still important in 2020 for any WordPress website. With that in mind, now we’re going to tell you about some email marketing plugins you can use to get started. This list is no particular order, these are just the widely used plugins.
#1. MailChimp (MC4WP)
First of all, we’ve got MailChimp. It’s unarguably the most popular email marketing service right now for WordPress based websites, and there are a number of reasons behind its popularity. The chief among them is its ease of use and flexibility, which allows you to create custom sign-up forms, landing pages, newsletters and other campaign elements. It also works well with WooCommerce and other e-commerce solutions developed for WordPress. The free version allows up to 2,000 subscribers and 12,000 emails per month.
#2. SendInBlue
Next, we have the SendInBlue email marketing plugin that comes with a drag-and-drop email creation tool and pretty much every other feature that is offered by MailChimp. It provides you real-time statistics on how your emails are doing and also provides professional support for all those times when you need some help. However, you need to be using the SendInBlue email marketing service to use this plugin. The free version of the plugin allows you to send up to 300 emails per day.
#3. Newsletter
The functionality of this plugin is as simple as its name – just install it, and you can start collecting emails immediately without having to go through any complex setup. Newsletters can be created with the help of a drag-and-drop tool that comes built into it, and a central status panel can be used to monitor the performance of all your emails. A different thing about it is the 20+ extensions that can be purchased to make it even more powerful. The extensions are available as a part of its Premium service.
#4. Mailster
Now, let’s talk about Mailster. The difference between Mailster and other plugins mentioned above is that it doesn’t require you to use their own email marketing service. You can use any email marketing service, and it’ll work just fine with it. In addition to that, it’s a premium plugin and no free option is available. Some of its unique features include sending emails based on specific triggers, a large library of templates and more detailed analytics about your emails.
#5. MailPoet
MailPoet offers more than 50 templates to get you started. You can drag and drop sections to customize it to your liking. You can send out emails automatically whenever you make a new post on your blog. You can also send out welcome emails when on autopilot when someone new subscribes. However, with the free version, you are limited to 1000 subscribers. The premium version of the plugin is priced according to the size of your email list.
#6. OptinMonster
OptinMonster is a popular email marketing tool that helps you generate leads. It integrates and works seamlessly for WordPress websites. It offers unique features like Geo-location targeting and targeted messaging by observing the user’s mouse behavior. It also comes with conversion-optimized templates, a powerful segmentation engine that helps you target the correct audience and advanced insights into your campaigns.
#7. Bloom
Bloom is an email opt-in plugin for WordPress by Elegant Themes. It allows you to create highly targeted email marketing campaigns, based on the user’s location and interactions with the content. You can choose from over 100 templates and 6 different display types. Easily set up the pop-ups and Fly-ins to be triggered by different activities like ‘After inactivity’ or ‘After commenting’.
#8. SendPress
SendPress is a WordPress newsletter plugin with no limit on the number of subscribers even with the free version. It comes with an easy to use Editor and email tracking. The pro version includes HTML Templates, Advanced reports, 3rd Party Sending, Custom Fields and Post Notification.
#9. MailOptin
MailOptin helps you grow your email list as well as automate your email marketing process. Lead Generation features include Lightbox Pop-Up, Floating Notification Bar, and Slide-in box. They help grab the user’s attention without being disruptive. You can also choose to display the opt-in form in the Sidebar or any other widget space, before or after a post or embedded inline. As for automation, you can automatically send out emails when you publish content, schedule newsletters, and email campaigns.
Conclusion
So that was our brief introduction for you about the importance of email marketing, and 4 popular email marketing plugins available for WordPress. If you still have any questions on the subject, feel free to leave them in the comments and we’ll try our best to answer them. Also, share this post so others who may be having the same questions about email marketing can get their answers.
It’s the oldest way to market your product. But has it also become old-fashioned?
In this age of social media marketing and chatbots, the debate has heated up on the relevance of email marketing. And yet, marketers continue to use it and swear by its benefits.
So, should you include email marketing in your marketing strategy or not?
And if you do, which plugin or service do you use?
We’re going to answer both questions for you in this article.
First, we’ll take a look at 5 reasons why email marketing is still relevant for any WordPress website, and then we’ll introduce you to some popular email marketing plugins and services that are available for WordPress. So without taking any more time, lets jump straight into it:
Reasons why Email Marketing is important for your WordPress website
First of all, email marketing is more effective than social media marketing from a conversion perspective.
Why? Because your social media posts might be missed by a lot of your fans and followers. What if someone doesn’t open up Facebook that day?
But when you send out an email it reaches every single subscriber.
So the reach is way higher than any of the social media platforms. When the reach is higher, the traffic you get is also higher.
Don’t get me wrong – social media marketing is important to generate new leads in any modern marketing strategy, but if you want to convert those leads into customers and repeat customers then email marketing is the way to go.
2. It makes you independent
The second good thing about email marketing is that it makes you independent.
With Social Media marketing you depend on the rules of Facebook and Twitter, while in search engine marketing you depend on Google. If any of these companies change their algorithms (which they often do), your traffic takes a beating.
However, with email marketing, there is no such problem. Once you’ve built a list of subscribers, it’s completely up to you to use it any way you please.
3. It’s cost-effective
Email marketing is very cost-effective when compared to any other method of marketing. Once you’ve built a sizable list of email subscribers, you can share your content with them without spending a ton of time and money.
All you need to do is invest in a good email marketing automation plugin, and that’s all. Depending on the resources available in your organization you may also need to hire someone to create the content for email marketing, but still, your total money spent on it will be much less while your ROI is much higher than other marketing channels.
4. It’s customizable
Email marketing is also customizable. You can generate a variety of email lists from your site by serving different types of content to different audiences. Then each of those lists can be targeted with the help of customized emails and content to maximize the results.
For instance, if you run an e-commerce site, your customers can subscribe to updates about a product that has sold out. Then as soon as the product is back in stock, they can be notified of it automatically. Similarly, if you sell downloadable products (i.e. online course, ebook, etc.) then you can build separate lists for your free and paid subscribers, providing them access to different types of content.
5. It’s measurable
Finally, email marketing is also highly measurable. You can track the results of every single campaign that you run with email marketing and every single event that took place with your emails.
From the opening of mails to bounce rate to unsubscribe rate to links clicked, everything can be tracked with complete accuracy. You can also perform split tests or A/B tests on your emails, and their results can also be measured. There’s no guesswork involved, which helps you in optimizing your marketing campaigns effectively.
Best Email marketing plugins
We just told you 5 of the many reasons why email marketing is still important in 2020 for any WordPress website. With that in mind, now we’re going to tell you about some email marketing plugins you can use to get started. This list is no particular order, these are just the widely used plugins.
#1. MailChimp (MC4WP)
First of all, we’ve got MailChimp. It’s unarguably the most popular email marketing service right now for WordPress based websites, and there are a number of reasons behind its popularity. The chief among them is its ease of use and flexibility, which allows you to create custom sign-up forms, landing pages, newsletters and other campaign elements. It also works well with WooCommerce and other e-commerce solutions developed for WordPress. The free version allows up to 2,000 subscribers and 12,000 emails per month.
#2. SendInBlue
Next, we have the SendInBlue email marketing plugin that comes with a drag-and-drop email creation tool and pretty much every other feature that is offered by MailChimp. It provides you real-time statistics on how your emails are doing and also provides professional support for all those times when you need some help. However, you need to be using the SendInBlue email marketing service to use this plugin. The free version of the plugin allows you to send up to 300 emails per day.
#3. Newsletter
The functionality of this plugin is as simple as its name – just install it, and you can start collecting emails immediately without having to go through any complex setup. Newsletters can be created with the help of a drag-and-drop tool that comes built into it, and a central status panel can be used to monitor the performance of all your emails. A different thing about it is the 20+ extensions that can be purchased to make it even more powerful. The extensions are available as a part of its Premium service.
#4. Mailster
Now, let’s talk about Mailster. The difference between Mailster and other plugins mentioned above is that it doesn’t require you to use their own email marketing service. You can use any email marketing service, and it’ll work just fine with it. In addition to that, it’s a premium plugin and no free option is available. Some of its unique features include sending emails based on specific triggers, a large library of templates and more detailed analytics about your emails.
#5. MailPoet
MailPoet offers more than 50 templates to get you started. You can drag and drop sections to customize it to your liking. You can send out emails automatically whenever you make a new post on your blog. You can also send out welcome emails when on autopilot when someone new subscribes. However, with the free version, you are limited to 1000 subscribers. The premium version of the plugin is priced according to the size of your email list.
#6. OptinMonster
OptinMonster is a popular email marketing tool that helps you generate leads. It integrates and works seamlessly for WordPress websites. It offers unique features like Geo-location targeting and targeted messaging by observing the user’s mouse behavior. It also comes with conversion-optimized templates, a powerful segmentation engine that helps you target the correct audience and advanced insights into your campaigns.
#7. Bloom
Bloom is an email opt-in plugin for WordPress by Elegant Themes. It allows you to create highly targeted email marketing campaigns, based on the user’s location and interactions with the content. You can choose from over 100 templates and 6 different display types. Easily set up the pop-ups and Fly-ins to be triggered by different activities like ‘After inactivity’ or ‘After commenting’.
#8. SendPress
SendPress is a WordPress newsletter plugin with no limit on the number of subscribers even with the free version. It comes with an easy to use Editor and email tracking. The pro version includes HTML Templates, Advanced reports, 3rd Party Sending, Custom Fields and Post Notification.
#9. MailOptin
MailOptin helps you grow your email list as well as automate your email marketing process. Lead Generation features include Lightbox Pop-Up, Floating Notification Bar, and Slide-in box. They help grab the user’s attention without being disruptive. You can also choose to display the opt-in form in the Sidebar or any other widget space, before or after a post or embedded inline. As for automation, you can automatically send out emails when you publish content, schedule newsletters, and email campaigns.
Conclusion
So that was our brief introduction for you about the importance of email marketing, and 4 popular email marketing plugins available for WordPress. If you still have any questions on the subject, feel free to leave them in the comments and we’ll try our best to answer them. Also, share this post so others who may be having the same questions about email marketing can get their answers.
React Hooks are a new addition in React 16.8 that let you use state and other React features without writing a class component. In other words, Hooks are functions that let you “hook into” React state and lifecycle features from function components. (They do not work inside class components.)
React provides a few built-in Hooks like useState. You can also create your own Hooks to reuse stateful behavior between different components. The example below shows a counter whose state is managed using the useState() hook. Each time you click on the button, we make use of setCount() to update the value of count by 1.
This example renders a counter with a value of 0. When you click the button, it increments the value by 1. The initial value of the component is defined using useState.
const [count, setCount] = useState(0)
As you can see, we set that to be 0. Then we use the onClick() method to call setCount when we want to increment the value.
<button onClick={() => setCount(count + 1)}>
Click me
</button>
Before the release of React Hooks, this example would have used more lines of code, as we’d have had to make use of a class component.
Rules Of React Hooks
Before we dive deep into the best practices, we need to understand the rules of React Hooks which are also some of the fundamental concepts of the practices presented in this article.
React Hooks are JavaScript functions, but you need to follow two rules when using them.
Note: These two rules were introduced in React Hooks, as opposed to being part of JavaScript itself.
Let’s look at these rules in more detail.
Call Hooks At The Top Level
Don’t call Hooks inside loops, conditions, or nested functions. Always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.
Let’s make a Form component which will have two states:
accountName
accountDetail
These states will have default values, we’ll make use of the useEffect hook to persist the state to either the local storage of our browser or to the title of our document.
Now, this component will be maybe to successfully manage its state if it remains the same between multiple calls of useState and useEffect.
function Form() {
// 1. Use the accountName state variable
const [accountName, setAccountName] = useState('David');
// 2. Use an effect for persisting the form
useEffect(function persistForm() {
localStorage.setItem('formData', accountName);
});
// 3. Use the accountDetail state variable
const [accountDetail, setAccountDetail] = useState('Active');
// 4. Use an effect for updating the title
useEffect(function updateStatus() {
document.title = accountName + ' ' + accountDetail;
});
// ...
}
If the order of our Hooks changes (which can be possible when they are called in loops or conditionals), React will have a hard time figuring out how to preserve the state of our component.
// ------------
useState('David') // 1. Initialize the accountName state variable with 'David'
useEffect(persistForm) // 2. Add an effect for persisting the form
useState('Active') // 3. Initialize the accountdetail state variable with 'Active'
useEffect(updateStatus) // 4. Add an effect for updating the status
// -------------
// Second render
// -------------
useState('David') // 1. Read the accountName state variable (argument is ignored)
useEffect(persistForm) // 2. Replace the effect for persisting the form
useState('Active') // 3. Read the accountDetail state variable (argument is ignored)
useEffect(updateStatus) // 4. Replace the effect for updating the status
// ...
That’s the order React follows to call our hooks. Since the order remains the same, it will be able to preserve the state of our component. But what happens if we put a Hook call inside a condition?
// 🔴 We're breaking the first rule by using a Hook in a condition
if (accountName !== '') {
useEffect(function persistForm() {
localStorage.setItem('formData', accountName);
});
}
The accountName !== '' condition is true on the first render, so we run this Hook. However, on the next render the user might clear the form, making the condition false. Now that we skip this Hook during rendering, the order of the Hook calls becomes different:
useState('David') // 1. Read the accountName state variable (argument is ignored)
// useEffect(persistForm) // 🔴 This Hook was skipped!
useState('Active') // 🔴 2 (but was 3). Fail to read the accountDetails state variable
useEffect(updateStatus) // 🔴 3 (but was 4). Fail to replace the effect
React wouldn’t know what to return for the second useState Hook call. React expected that the second Hook call in this component corresponds to the persistForm effect, just like during the previous render — but it doesn’t anymore. From that point on, every next Hook call after the one we skipped would also shift by one — leading to bugs.
This is why Hooks must be called on the top level of our components. If we want to run an effect conditionally, we can put that condition inside our Hook.
Note: Check out the React Hook docs to read more on this topic.
Only Call Hooks From React Components
Don’t call Hooks from regular JavaScript functions. Instead, you can call Hooks from React function components. Let’s take look at the difference between JavaScript function and React component below:
Here we import the useState hook from the React package, and then declared our function. But this is invalid as it is not a React component.
React Function
import React, { useState} from "react";
import ReactDOM from "react-dom";
function Account(props) {
const [name, setName] = useState("David");
return <p>Hello, {name}! The price is <b>{props.total}</b> and the total amount is <b>{props.amount}</b></p>
}
ReactDom.render(
<Account total={20} amount={5000} />,
document.getElementById('root')
);
Even though the body of both looks similar, the latter becomes a component when we import React into the file. This is what makes it possible for us to use things like JSX and React hooks inside.
If you happened to import your preferred hook without importing React (which makes it a regular function), you will not be able to make use of the Hook you’ve imported as the Hook is accessible only in React component.
Call Hooks From Custom Hooks
A custom Hook is a JavaScript function whose name starts with use and that may call other Hooks. For example, useUserName is used below a custom Hook that calls the useState and useEffect hooks. It fetches data from an API, loops through the data, and calls setIsPresent() if the specific username it received is present in the API data.
We can then go on to reuse the functionality of this hook in other places where we need such in our application. In such places, except when needed, we don’t have to call useState or useEffect anymore.
By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.
ESLint Plugin
ESLint plugin called eslint-plugin-react-hooks enforces the rules above. This comes in handy in enforcing the rules when working on a project. I suggest you make use of this plugin when working on your project, especially when working with others. You can add this plugin to your project if you’d like to try it:
This plugin is included by default in Create React App. So you don’t need to add it if you bootstrap your React applications using Create-React-App.
Thinking In Hooks
Let’s take a brief look at class components and functional components (with Hooks), before diving into the few Hooks best practices.
The simplest way to define a component in React is to write a JavaScript function that returns a React element:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
The Welcome component accepts props which is an object that contains data and returns a React element. We can then import and render this component in another component.
The class component uses a programming methodology called Encapsulation which basically means that everything relevant to the class component will live within it. Life-cycle methods (constructors, componentDidMount(), render, and so on) give components a predictable structure.
Encapsulation is one of the fundamentals of OOP (Object-Oriented Programming). It refers to the bundling of data within the methods that operate on that data, and is used to hide the values or state of a structured data object inside a class — preventing unauthorized parties’ direct access to them.
With Hooks, the composition of a component changes from being a combination of life-cycle Hooks — to functionalities with some render at the end.
Function Component
The example below shows how custom Hooks can be used in a functional component (without showcasing what the body is). However, what it does or can do is not limited. It could be instantiating state variables, consuming contexts, subscribing the component to various side effects — or all of the above if you’re using a custom hook!
function {
useHook{...};
useHook{...};
useHook{...};
return (
...
);
}
Class Component
A class component requires you to extend from React.Component and create a render function which returns a React element. This requires more code but will also give you some benefits.
There are some benefits you get by using functional components in React:
It will get easier to separate container and presentational components because you need to think more about your component’s state if you don’t have access to setState() in your component.
Functional components are much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks.
You end up with less code.
The React team mentioned that there may be a performance boost for functional components in future React versions.
This leads to the first best practice when using React Hooks.
Hooks Best Practices
1. Simplify Your Hooks
Keeping React Hooks simple will give you the power to effectively control and manipulate what goes on in a component throughout its lifetime. Avoid writing custom Hooks as much as possible; you can inline a useState() or useEffect() instead of creating your own hook.
If you find yourself making use of a bunch of custom Hooks that are related in functionality, you can create a custom hook that acts as a wrapper for these. Let’s take a look at two different functional components with hooks below.
Functional Component v1
function {
useHook(...);
useHook(...);
useHook(...);
return(
<div>...</div>
);
}
Functional Component v2
function {
useCustomHook(...);
useHook(...);
useHook(...);
return(
<div>...</div>
);
}
v2 is a better version because it keeps the hook simple and all other useHooks are inline accordingly. This allows us to create functionality that can be reused across different components and also gives us more power to control and manipulate our components effectively. Instead of adopting v1 in which our components are littered with Hooks, you should make use of v2 which will make debugging easy and your code cleaner.
2. Organize And Structure Your Hooks
One of the advantages of React Hooks is the ability to write less code that is easy to read. In some cases, the amount of useEffect() and useState() can still be confusing. When you keep your component organized it will help in readability and keep the flow of your components consistent and predictable. If your custom Hooks are too complicated, you can always break them down to sub-custom Hooks. Extract the logic of your component to custom Hooks to make your code readable.
3. Use React Hooks Snippets
React Hooks Snippets is a Visual Studio Code extension to make React Hooks easier and faster. Currently, five hooks are supported:
useState()
useEffect()
useContext()
useCallback()
useMemo()
Other snippets have also been added. I have tried working with these Hooks and it has been one of the best practices I’ve personally used while working with them.
There are two ways you can add React Hooks snippets to your project:
Command
Launch the VS Code Quick open (Ctrl+P), paste ext install ALDuncanson.react-hooks-snippets and press Enter.
Extension Marketplace
Launch ‘VS Code Extension Marketplace’ (Ctrl+Shift+X) and search for ‘React Hook Snippets’. Then, look for the ‘Alduncanson’ icon.
I recommend the first snippet. Read more about the snippets here or check for the lastest Hooks snippets here.
4. Put Hooks Rules Into Consideration
Endeavor to always put the two rules of Hooks we learned earlier into consideration while working with React Hooks.
Only call your Hooks at the top level. Don’t call Hooks inside loops, conditions or nested functions.
Always call Hooks from React function components or from custom Hooks, don’t call Hooks from regular JavaScript functions.
The ESlint plugin called eslint-plugin-react-hooks enforces these two rules, you can add this plugin to your project if you’d like it as we explain above in rules of hooks section.
Best practices have not been fully resolved because Hooks are still relatively new. So adoption should be taken with precaution one would take in adopting in any early technology. With that in mind, Hooks are the way for the future of React.
Conclusion
I hope you enjoyed this tutorial. We’ve learned the two most important rules of React Hooks and how to effectively think in Hooks. We looked at functional components and some best practices in writing Hooks the right and effective way. As brief as the rules are, it’s important to make them your guiding compass when writing rules. If you are prone to forget it, you can make use of the ESLint plugin to enforce it.
I hope you will take all of the lessons learned here in your next React project. Good luck!
Side projects can help to demonstrate your passion and enthusiasm for design to future clients or employers and can create a great new addition to your design portfolio. Side projects are a way you can work on things you want to work on — rather than just ones which are bringing in the money. Whether it turns out to be artistic or experimental, it can be great in taking you out of your everyday routine and leave you with a true feeling of satisfaction.
There’s never been a better time to start a side project. Here are some of our favorite designer side projects, guaranteed to inspire.
Christopher Simmons – The message is medium rare
The Message is Medium Rare was a side project created by designer Christopher Simmons, who runs MINE, a San Francisco design office. He wanted a side project to find inspiration and stay creative and found that through looking at the world both critically and in wonder, that there were lessons to be learnt everywhere and insights to be had.
He decided to investigate this idea by eating a burger a week and sharing the lessons each one teaches. The design and concept of the project is wonderfully simple, yet easy to get lost in amidst the hidden meanings sandwiched between slices of bread, beef and ketchup. The project has featured in many press outlets and is a great example of how a side project can raise your profile.
Davey Heuser – IconJar
Dutch designer Davey Heuser decided to take on a side project a few years ago, developing IconJar with fellow designer Curtis Hard. A Mac App for organizing and managing icons. It is essentially a library container that allows you to drop any icon in any format and organise them into sets (collections) and groups (folders). It’s easy to use and to export your icons both quickly and accurately.
It’s a great side project that is used by some of the biggest companies out there, including Google, Shopify, and Microsoft.
Frank Chimero – The Shape of Design
NYC-based designer Frank Chimero decided to self-publish a book as his side project. Back in 2011 he created the book The Shape of Design, a small handbook about designing that Frank wished was available to him when he began his own career in the field.
The concept was originally given as a talk by Frank at the Build Conference back in November 2010, where he was encouraged by the response and decided to expand on some of its themes in a book. It’s now used in design classrooms all around the world as foundational reading and has grown its audience to include chefs, woodworkers, writers and other creatives, all of which praise the book highly.
Nguyen Le – Process Masterclass
Nguyen Lee is an independent designer based in Melbourne who decided to start a side project teaching others about design. He called this Process Masterclass and it focuses on teaching new and aspiring designers how to improve their skills, provide more excellent value to their clients and create reliable design processes.
Over 1,000 designers have taken the course and this includes those who have worked at large companies such as Slack, Stripe, Framer, Ueno, Instrument, and Huge inc.
Lauren Hom – Passion to Paid
Passion to Paid is the side project of designer Lauren Hom and is an online creative bootcamp on how to create a killer passion project that will kickstart your career. Lauren cites side projects as the no.1 reason she was able to grow her business as a freelance illustrator and find success at such a young age and this course is here to help others do the same.
Content includes how to improve your lettering skills, how to get paid for your work, and how to come up with your next big idea. The Passion to Paid course is currently paused until mid-2020, but you can join the waitlist.
Chandan Mishra – Design Languages
Chandan Mishra is a designer from Pune, India whose side project is Design Languages. Developed with Varun Srinivas, it is a curated list of design languages and systems from a range of companies. It was born from the frustration of having to hunt for and research design systems, wasting time and hitting dead ends. It is a essentially a curated library for design languages, design systems, and front-end frameworks and it’s free to use too!
Jessica Hische – Should I Work For Free?
In 2011 Jessica Hisch put together “Should I work for free” a flowchart which helps you decide if you should work on that project for free or not. In short, if the client is not someone you owe big time, you shouldn’t. Jessica is a letterer and was bored of people asking her to work for “free” or for “exposure.”
As well as the flowchart which you can download, Jessica also writes a blog and gives talk on design as well as running an online store where you can purchase prints, cards and her own custom fonts.
Edoardo Rainoldi – Rooki.design
Rooki.design is the brainchild of Edoardo Rainoldi, a young digital product designer born in Italy but who travelled all around the world to work and study. The site was born from frustration in finding good, free resources for design students. Being a student himself, Edoardo found most articles and interviews online were catered for experienced designers and not those young, creative minds that need the help to start and grow.
All interviews and resources are catered for the young designer demographic and are free of charge.
Davide Baratta – TypoStories
Typostories is a side project that was created by Davide Baratta, the design lead at Impero. It is a study about typefaces and font pairings and was created from the want to explore diverse typographic solutions while also staying up to date with the newest releases from his favorite independent type foundries. The site offers a study into typefaces and font pairings and features an assortment of typographic illustrations he was inspired to create.
You can currently see Vol.1 and he is working on Vol.2.
Nicole Saidy – To Inspire About Design
Nicole Saidy is a digital designer from Beirut and wanted to start a side project to help inspire and teach people about design. She does this through her website, with many useful resources to help with designers — both established and newcomers — and also as a speaker and course author.
Her course “become a UI/UX designer” is made for those overwhelmed beginners who want to kickstart their career and has many helpful hints and tips.
The expenditure on public cloud services in the last 2018 was around $160 Billion according to the International Data Corporation.
The global cloud market is expected to go over $650 Billion by the end of the year 2025. According to the statistics of 2020, 70% of the total expenditure on technical was covered by the cloud. As most of the organizations are going serverless, this is the market of the cloud has been extended so widely that now almost 84% of the enterprises opt for a multi-cloud strategy. Cloud adoption has become the priority of most of the IT infrastructures and is expected to maintain its popularity in the market for many years to come.
A question might arise in the minds of the readers that what is so miraculous and demanding in cloud computing services?
Using and running software seamlessly without even installing it is the beauty of cloud computing. Even the installed software cannot bring the level of redundancy, stability, and security that cloud computing software brings in the infrastructure.
Also, if you want to know more about how your data is stored in the cloud, make sure to check What is cloud storage guide. The other beauty that cannot go unmentioned is the flexibility that cloud services bring on board by allowing any kind of enterprise and of any size. There are many enterprises that are not able to afford or do not have that technical expertise to support extended resources. For them managed cloud services come at the rescue as an excellent solution. The plethora of content and other means that cloud hosting providers is impossible to even imagine with any other platform. Different types of cloud services i.e. IaaS, PaaS, and SaaS have been contributing and capturing the market at different levels. These services contribute the most in the quarterly revenues of all the software vendors.
If you have already realized the importance of cloud for your business, but if you haven’t then cloud migration should be the next footstep to give that required edge to your business. A single migration takes account into many factors but the benefits involved make the procedure unquestionable. There might be some risks involved also when your infrastructure is not designed to withstand the cloud module. Now the question arises whether it is worth taking the risk? The answer is a hundred times YES.
Do companies need to know about the technical specifications of cloud migration? Yes, because then the company would be operated in the hands of the own dedicated cloud service or any external cloud service provider for so many years to come. So without wasting any further time let’s get into the requirements before, in and after cloud migration in detail.
Pre-requisites of migration
Future prospect of the business-Before migrating to the cloud, the company should definitely foresee all the future prospects of the business with the help of the researchers and analyzers. The envision of future needs will only be the deciding factor whether your business requires cloud migration or not. Hence a strategy must be prepared and each concerned person must be fully aware of the circumstances and results. To come up to the best decision, the company should go through the pros and cons of cloud migration and get proper feedback from already cloud migrated enterprises for better understanding.
Outlining the cloud model – Once the business gets migrated to the cloud, roles and responsibilities change for many team members of the organization. Hence, each member must be properly informed about the changes in the infrastructure. In this way, the duties are separated and business activities are ensured. It also involves identifying and understanding the workloads and what are their supporting systems. The best way of doing this is by discovering elements like application to application, application to VM and VM to physical machine dependencies. After this has been done, deciding for the number of accounts a company will have or should be given grant access to.
Training the staff – Migrating to the cloud is not the end solution making your staff adaptable to the cloud environment is also a sole responsibility for any company. Once the whole staff gets that required technical expertise, things become more smooth and at a fast pace. But this should happen at a very early stage as any delay in this may lead to disruptions at the organizational level.
Capturing current and targets by KPIs-Capturing current performance and what can be the future capabilities. Though this might require coordination with different stakeholders and other issues involved. In spite of these issues, understanding the current performance baselines should be the immediate action for any enterprise which is going for cloud migration. In the middle of this not forgetting about the targets that you would have dreamt of for your company should not be ignored.Setting the KPIs (Key Performance Indicators) would be the approach to this. The staff that has expertise in the domain should look out whether the targets are aligned with the new cloud environment and if not then what changes are required.
Selecting the best cloud service provider- Once you have gone through all the prerequisites, the major step comes of selecting the best and most suitable cloud service provider for your business. There is no harm in trying out multiple options before deciding for that one.
Steps during migration
Automation- Any cloud platforms’ dexterity can be tested through automation. Try to automate most of the operations and if possible all. To achieve the highest level of automation, the structure of the organization should be consistent and transparent and this might demand a stretched time.
Transform the internal processes- To enjoy the maximum efficiency of any cloud service it is very important that the conventional internal processes must be transformed accordingly. More the number of processes will be transformed and aligned to the cloud platform; more empowered will be your business. All the BI applications must be migrated along with the custom reporting tools and data applications.
Post migration
Monitoring is mandatory- Even after the migration has been successfully done, the system requires 24/7 monitoring to ensure whether all the processes are in line with the architecture. Even a single ignorance within the infrastructure can lead to future losses.
Ensure cloud-native monitoring tools– Although there are multiple tools available, an expert like cloud needs the best cloud-native monitoring tool so as to find the bestway to fit into the business.
Keep the single point of contact- If you have purchased the cloud-based service from a reputed cloud service provider, and then it would be for the best that a single point of contact should be kept with the support centre of your cloud service provider.
All these steps performed at the right time during cloud migration can literally bring miracles in your business. Cloud migration must be carried out in accordance with the best practices. But apart from all this, the onus lies on you to keep a track of the records and results, benchmarks to be set and what would be the deviations. All this together will ensure a successful cloud migration and your company reaching the optimum level of ROI.
Looking to share code between your Vue components? If you’re familiar with Vue 2, you’ve probably used a mixin for this purpose. But the new Composition API, which is available now as a plugin for Vue 2 and an upcoming feature of Vue 3, provides a much better solution.
In this article, we’ll take a look at the drawbacks of mixins and see how the Composition API overcomes them and allows Vue applications to be far more scalable.
Mixins in a nutshell
Let’s quickly review the mixins pattern as it’s important to have it top-of-mind for what we’ll cover in the next sections.
Normally, a Vue component is defined by a JavaScript object with various properties representing the functionality we need — things like data, methods, computed, and so on.
Now we can add this mixin to any consuming component by assigning it to the mixin config property. At runtime, Vue will merge the properties of the component with any added mixins.
Back in mid-2016, Dan Abramov wrote “Mixins Considered Harmful” in which he argues that using mixins for reusing logic in React components is an anti-pattern, advocating instead to move away from them.
The same drawbacks he mentions about React mixins are, unfortunately, applicable to Vue as well. Let’s get familiar with these drawbacks before we take a look at how the Composition API overcomes them.
Naming collisions
We saw how the mixin pattern merges two objects at runtime. What happens if they both share a property with the same name?
This is where the merge strategy comes into play. This is the set of rules to determine what happens when a component contains multiple options with the same name.
The default (but optionally configurable) merge strategy for Vue components dictates that local options will override mixin options. There are exceptions though. For example, if we have multiple lifecycle hooks of the same type, these will be added to an array of hooks and all will be called sequentially.
Even though we shouldn’t run into any actual errors, it becomes increasingly difficult to write code when juggling named properties across multiple components and mixins. It’s especially difficult once third-party mixins are added as npm packages with their own named properties that might cause conflicts.
Implicit dependencies
There is no hierarchical relationship between a mixin and a component that consumes it. This means that a component can use a data property defined in the mixin (e.g. mySharedDataProperty) but a mixin can also use a data property it assumes is defined in the component (e.g. myLocalDataProperty). This is commonly the case when a mixin is used to share input validation. The mixin might expect a component to have an input value which it would use in its own validate method.
This can cause problems, though. What happens if we want to refactor a component later and change the name of a variable that the mixin needs? We won’t notice, looking at the component, that anything is wrong. A linter won’t pick it up either. We’ll only see the error at runtime.
Now imagine a component with a whole bunch of mixins. Can we refactor a local data property, or will it break a mixin? Which mixin? We’d have to manually search them all to know.
Migrating from mixins
Dan’s article offers alternatives to mixins, including higher-order components, utility methods, and some other component composition patterns.
While Vue is similar to React in many ways, the alternative patterns he suggests don’t translate well to Vue. So, despite this article being written in mid-2016, Vue developers have been suffering with mixin issues ever since.
Until now. The drawbacks of mixins were one of the main motivating factors behind the Composition API. Let’s get a quick overview of how it works before we look at how it overcomes the issues with mixins.
Composition API crash course
The key idea of the Composition API is that, rather than defining a component’s functionality (e.g. state, methods, computed properties, etc.) as object properties, we define them as JavaScript variables that get returned from a new setup function.
Take this classic example of a Vue 2 component that defines a “counter” feature:
You’ll first notice we import a ref function, which allows us to define a reactive variable that functions pretty much the same as a data variable. Same story for the computed function.
The increment method is not reactive so it can be declared as a plain JavaScript function. Notice that we need to change the sub-property value in order to change the value of the count reactive variable. That’s because reactive variables created using ref need to be objects to retain their reactivity as they’re passed around.
It’s a good idea to consult the the Vue Composition API docs for a detailed explanation of how ref works.
Once we’ve defined these features, we return them from the setup function. There is no difference in functionality between the two components above. All we did was use the alternative API.
Tip: the Composition API will be a core feature of Vue 3, but you can also use it in Vue 2 with the NPM plugin @vue/composition-api.
Code extraction
The first clear advantage of the Composition API is that it’s easy to extract logic.
Let’s refactor the component defined above with the Composition API so that the features we defined are in a JavaScript module useCounter. (Prefixing a feature’s description with “use” is a Composition API naming convention.)
To consume that feature in a component, we simply import the module into the component file and call it (noting that the import is a function). This returns the variables we defined, and we can subsequently return these from the setup function.
This may all seem a bit verbose and pointless at first, but let’s see how this pattern overcomes the issues with mixins we looked at earlier.
Naming collisions… solved!
We saw before how a mixin can use properties that may have the same name as those in the consuming component, or even more insidiously, in other mixins used by the consuming component.
This is not an issue with the Composition API because we need to explicitly name any state or methods returned from a composition function:
Naming collisions will be resolved the same way they are for any other JavaScript variable.
Implicit dependencies… solved!
We also saw before how a mixin may use data properties defined on the consuming component, which can make the code fragile and very hard to reason about.
A composition function can also call on a local variable defined in the consuming component. The difference, though, is that this variable must now be explicitly passed to the composition function.
import useCompFunction from "./useCompFunction";
export default {
setup () {
// some local value the a composition function needs to use
const myLocalVal = ref(0);
// it must be explicitly passed as an argument
const { ... } = useCompFunction(myLocalVal);
}
}
Wrapping up
The mixin pattern looks pretty safe on the surface. However, sharing code by merging objects becomes an anti-pattern due to the fragility it adds to code and the way it obscures the ability to reason about the functionality.
The most clever part of the Composition API is that it allows Vue to lean on the safeguards built into native JavaScript in order to share code, like passing variables to functions, and the module system.
Does that mean the Composition API is superior in every way to Vue’s classic API? No. In most cases you’ll be fine to stick with the classic API. But if you’re planning to reuse code, the Composition API is unquestionably superior.