Integrity
Write
Loading...
Tim Denning

Tim Denning

7 months ago

I gave up climbing the corporate ladder once I realized how deeply unhappy everyone at the top was.

More on Personal Growth

Matthew Royse

Matthew Royse

10 months ago

7 ways to improve public speaking

How to overcome public speaking fear and give a killer presentation

Photo by Kenny Eliason on Unsplash

"Public speaking is people's biggest fear, according to studies. Death's second. The average person is better off in the casket than delivering the eulogy."  — American comedian, actor, writer, and producer Jerry Seinfeld

People fear public speaking, according to research. Public speaking can be intimidating.

Most professions require public speaking, whether to 5, 50, 500, or 5,000 people. Your career will require many presentations. In a small meeting, company update, or industry conference.

You can improve your public speaking skills. You can reduce your anxiety, improve your performance, and feel more comfortable speaking in public.

If I returned to college, I'd focus on writing and public speaking. Effective communication is everything.” — 38th president Gerald R. Ford

You can deliver a great presentation despite your fear of public speaking. There are ways to stay calm while speaking and become a more effective public speaker.

Seven tips to improve your public speaking today. Let's help you overcome your fear (no pun intended).

Know your audience.

"You're not being judged; the audience is." — Entrepreneur, author, and speaker Seth Godin

Understand your audience before speaking publicly. Before preparing a presentation, know your audience. Learn what they care about and find useful.

Your presentation may depend on where you're speaking. A classroom is different from a company meeting.

Determine your audience before developing your main messages. Learn everything about them. Knowing your audience helps you choose the right words, information (thought leadership vs. technical), and motivational message.

2. Be Observant

Observe others' speeches to improve your own. Watching free TED Talks on education, business, science, technology, and creativity can teach you a lot about public speaking.

What worked and what didn't?

  • What would you change?

  • Their strengths

  • How interesting or dull was the topic?

Note their techniques to learn more. Studying the best public speakers will amaze you.

Learn how their stage presence helped them communicate and captivated their audience. Please note their pauses, humor, and pacing.

3. Practice

"A speaker should prepare based on what he wants to learn, not say." — Author, speaker, and pastor Tod Stocker

Practice makes perfect when it comes to public speaking. By repeating your presentation, you can find your comfort zone.

When you've practiced your presentation many times, you'll feel natural and confident giving it. Preparation helps overcome fear and anxiety. Review notes and important messages.

When you know the material well, you can explain it better. Your presentation preparation starts before you go on stage.

Keep a notebook or journal of ideas, quotes, and examples. More content means better audience-targeting.

4. Self-record

Videotape your speeches. Check yourself. Body language, hands, pacing, and vocabulary should be reviewed.

Best public speakers evaluate their performance to improve.

Write down what you did best, what you could improve and what you should stop doing after watching a recording of yourself. Seeing yourself can be unsettling. This is how you improve.

5. Remove text from slides

"Humans can't read and comprehend screen text while listening to a speaker. Therefore, lots of text and long, complete sentences are bad, bad, bad.” —Communications expert Garr Reynolds

Presentation slides shouldn't have too much text. 100-slide presentations bore the audience. Your slides should preview what you'll say to the audience.

Use slides to emphasize your main point visually.

If you add text, use at least 40-point font. Your slides shouldn't require squinting to read. You want people to watch you, not your slides.

6. Body language

"Body language is powerful." We had body language before speech, and 80% of a conversation is read through the body, not the words." — Dancer, writer, and broadcaster Deborah Bull

Nonverbal communication dominates. Our bodies speak louder than words. Don't fidget, rock, lean, or pace.

Relax your body to communicate clearly and without distraction through nonverbal cues. Public speaking anxiety can cause tense body language.

Maintain posture and eye contact. Don’t put your hand in your pockets, cross your arms, or stare at your notes. Make purposeful hand gestures that match what you're saying.

7. Beginning/ending Strong

Beginning and end are memorable. Your presentation must start strong and end strongly. To engage your audience, don't sound robotic.

Begin with a story, stat, or quote. Conclude with a summary of key points. Focus on how you will start and end your speech.

You should memorize your presentation's opening and closing. Memorize something naturally. Excellent presentations start and end strong because people won't remember the middle.


Bringing It All Together

Seven simple yet powerful ways to improve public speaking. Know your audience, study others, prepare and rehearse, record yourself, remove as much text as possible from slides, and start and end strong.

Follow these tips to improve your speaking and audience communication. Prepare, practice, and learn from great speakers to reduce your fear of public speaking.

"Speaking to one person or a thousand is public speaking." — Vocal coach Roger Love

Neeramitra Reddy

Neeramitra Reddy

6 months ago

The best life advice I've ever heard could very well come from 50 Cent.

He built a $40M hip-hop empire from street drug dealing.

Free for creative use by PCMag

50 Cent was nearly killed by 9mm bullets.

Before 50 Cent, Curtis Jackson sold drugs.

He sold coke to worried addicts after being orphaned at 8.

Pursuing police. Murderous hustlers and gangs. Unwitting informers.

Despite his hard life, his hip-hop career was a success.

An assassination attempt ended his career at the start.

What sane producer would want to deal with a man entrenched in crime?

Most would have drowned in self-pity and drank themselves to death.

But 50 Cent isn't most people. Life on the streets had given him fearlessness.

“Having a brush with death, or being reminded in a dramatic way of the shortness of our lives, can have a positive, therapeutic effect. So it is best to make every moment count, to have a sense of urgency about life.” ― 50 Cent, The 50th Law

50 released a series of mixtapes that caught Eminem's attention and earned him a $50 million deal!

50 Cents turned death into life.

Things happen; that is life.

We want problems solved.

Every human has problems, whether it's Jeff Bezos swimming in his billions, Obama in his comfortable retirement home, or Dan Bilzerian with his hired bikini models.

All problems.

Problems churn through life. solve one, another appears.

It's harsh. Life's unfair. We can face reality or run from it.

The latter will worsen your issues.

“The firmer your grasp on reality, the more power you will have to alter it for your purposes.” — 50 Cent, The 50th Law

In a fantasy-obsessed world, 50 Cent loves reality.

Wish for better problem-solving skills rather than problem-free living.

Don't wish, work.

We All Have the True Power of Alchemy

Humans are arrogant enough to think the universe cares about them.

That things happen as if the universe notices our nanosecond existences.

Things simply happen. Period.

By changing our perspective, we can turn good things bad.

The alchemists' search for the philosopher's stone may have symbolized the ability to turn our lead-like perceptions into gold.

Negativity bias tints our perceptions.

Normal sparring broke your elbow? Rest and rethink your training. Fired? You can improve your skills and get a better job.

Consider Curtis if he had fallen into despair.

The legend we call 50 Cent wouldn’t have existed.

The Best Lesson in Life Ever?

Neither avoid nor fear your reality.

That simple sentence contains every self-help tip and life lesson on Earth.

When reality is all there is, why fear it? avoidance?

Or worse, fleeing?

To accept reality, we must eliminate the words should be, could be, wish it were, and hope it will be.

It is. Period.

Only by accepting reality's chaos can you shape your life.

“Behind me is infinite power. Before me is endless possibility, around me is boundless opportunity. My strength is mental, physical and spiritual.” — 50 Cent

Hudson Rennie

Hudson Rennie

5 months ago

My Work at a $1.2 Billion Startup That Failed

Sometimes doing everything correctly isn't enough.

Image via: glassdoor.com licensed under CC BY 2.0

In 2020, I could fix my life.

After failing to start a business, I owed $40,000 and had no work.

A $1.2 billion startup on the cusp of going public pulled me up.

Ironically, it was getting ready for an epic fall — with the world watching.

Life sometimes helps. Without a base, even the strongest fall. A corporation that did everything right failed 3 months after going public.

First-row view.

Apple is the creator of Adore.

Out of respect, I've altered the company and employees' names in this account, despite their failure.

Although being a publicly traded company, it may become obvious.

We’ll call it “Adore” — a revolutionary concept in retail shopping.

Two Apple execs established Adore in 2014 with a focus on people-first purchasing.

Jon and Tim:

  • The concept for the stylish Apple retail locations you see today was developed by retail expert Jon Swanson, who collaborated closely with Steve Jobs.

  • Tim Cruiter is a graphic designer who produced the recognizable bouncing lamp video that appears at the start of every Pixar film.

The dynamic duo realized their vision.

“What if you could combine the convenience of online shopping with the confidence of the conventional brick-and-mortar store experience.”

Adore's mobile store concept combined traditional retail with online shopping.

Adore brought joy to 70+ cities and 4 countries over 7 years, including the US, Canada, and the UK.

Being employed on the ground floor, with world dominance and IPO on the horizon, was exciting.

I started as an Adore Expert.

I delivered cell phones, helped consumers set them up, and sold add-ons.

As the company grew, I became a Virtual Learning Facilitator and trained new employees across North America using Zoom.

In this capacity, I gained corporate insider knowledge. I worked with the creative team and Jon and Tim.

Image via Instagram: @goenjoy

It's where I saw company foundation fissures. Despite appearances, investors were concerned.

The business strategy was ground-breaking.

Even after seeing my employee stocks fall from a home down payment to $0 (when Adore filed for bankruptcy), it's hard to pinpoint what went wrong.

Solid business model, well-executed.

Jon and Tim's chase for public funding ended in glory.

Here’s the business model in a nutshell:

Buying cell phones is cumbersome. You have two choices:

  1. Online purchase: not knowing what plan you require or how to operate your device.

  2. Enter a store, which can be troublesome and stressful.

Apple, AT&T, and Rogers offered Adore as a free delivery add-on. Customers could:

  • Have their phone delivered by UPS or Canada Post in 1-2 weeks.

  • Alternately, arrange for a person to visit them the same day (or sometimes even the same hour) to assist them set up their phone and demonstrate how to use it (transferring contacts, switching the SIM card, etc.).

Each Adore Expert brought a van with extra devices and accessories to customers.

Happy customers.

Here’s how Adore and its partners made money:

Adores partners appreciated sending Experts to consumers' homes since they improved customer satisfaction, average sale, and gadget returns.

**Telecom enterprises have low customer satisfaction. The average NPS is 30/100. Adore's global NPS was 80.

Adore made money by:

  • a set cost for each delivery

  • commission on sold warranties and extras

Consumer product applications seemed infinite.

A proprietary scheduling system (“The Adore App”), allowed for same-day, even same-hour deliveries.

It differentiates Adore.

They treated staff generously by:

  • Options on stock

  • health advantages

  • sales enticements

  • high rates per hour

Four-day workweeks were set by experts.

Being hired early felt like joining Uber, Netflix, or Tesla. We hoped the company's stocks would rise.

Exciting times.

I smiled as I greeted more than 1,000 new staff.

I spent a decade in retail before joining Adore. I needed a change.

After a leap of faith, I needed a lifeline. So, I applied for retail sales jobs in the spring of 2019.

The universe typically offers you what you want after you accept what you need. I needed a job to settle my debt and reach $0 again.

And the universe listened.

After being hired as an Adore Expert, I became a Virtual Learning Facilitator. Enough said.

After weeks of economic damage from the pandemic.

This employment let me work from home during the pandemic. It taught me excellent business skills.

I was active in brainstorming, onboarding new personnel, and expanding communication as we grew.

This job gave me vital skills and a regular paycheck during the pandemic.

It wasn’t until January of 2022 that I left on my own accord to try to work for myself again — this time, it’s going much better.

Adore was perfect. We valued:

  • Connection

  • Discovery

  • Empathy

Everything we did centered on compassion, and we held frequent Justice Calls to discuss diversity and work culture.

The last day of onboarding typically ended in tears as employees felt like they'd found a home, as I had.

Like all nice things, the wonderful vibes ended.

First indication of distress

My first day at the workplace was great.

Fun, intuitive, and they wanted creative individuals, not salesman.

While sales were important, the company's vision was more important.

“To deliver joy through life-changing mobile retail experiences.”

Thorough, forward-thinking training. We had a module on intuition. It gave us role ownership.

We were flown cross-country for training, gave feedback, and felt like we made a difference. Multiple contacts responded immediately and enthusiastically.

The atmosphere was genuine.

Making money was secondary, though. Incredible service was a priority.

Jon and Tim answered new hires' questions during Zoom calls during onboarding. CEOs seldom meet new hires this way, but they seemed to enjoy it.

All appeared well.

But in late 2021, things started changing.

Adore's leadership changed after its IPO. From basic values to sales maximization. We lost communication and were forced to fend for ourselves.

Removed the training wheels.

It got tougher to gain instructions from those above me, and new employees told me their roles weren't as advertised.

External money-focused managers were hired.

Instead of creative types, we hired salespeople.

With a new focus on numbers, Adore's uniqueness began to crumble.

Via Zoom, hundreds of workers were let go.

So.

Early in 2022, mass Zoom firings were trending. A CEO firing 900 workers over Zoom went viral.

Adore was special to me, but it became a headline.

30 June 2022, Vice Motherboard published Watch as Adore's CEO Fires Hundreds.

It described a leaked video of Jon Swanson laying off all staff in Canada and the UK.

They called it a “notice of redundancy”.

The corporation couldn't pay its employees.

I loved Adore's underlying ideals, among other things. We called clients Adorers and sold solutions, not add-ons.

But, like anything, a company is only as strong as its weakest link. And obviously, the people-first focus wasn’t making enough money.

There were signs. The expansion was presumably a race against time and money.

Adore finally declared bankruptcy.

Adore declared bankruptcy 3 months after going public. It happened in waves, like any large-scale fall.

  • Initial key players to leave were

  • Then, communication deteriorated.

  • Lastly, the corporate culture disintegrated.

6 months after leaving Adore, I received a letter in the mail from a Law firm — it was about my stocks.

Adore filed Chapter 11. I had to sue to collect my worthless investments.

I hoped those stocks will be valuable someday. Nope. Nope.

Sad, I sighed.

$1.2 billion firm gone.

I left the workplace 3 months before starting a writing business. Despite being mediocre, I'm doing fine.

I got up as Adore fell.

Finally, can we scale kindness?

I trust my gut. Changes at Adore made me leave before it sank.

Adores' unceremonious slide from a top startup to bankruptcy is astonishing to me.

The company did everything perfectly, in my opinion.

  • first to market,

  • provided excellent service

  • paid their staff handsomely.

  • was responsible and attentive to criticism

The company wasn't led by an egotistical eccentric. The crew had centuries of cumulative space experience.

I'm optimistic about the future of work culture, but is compassion scalable?

You might also like

Tim Denning

Tim Denning

4 months ago

One of the biggest publishers in the world offered me a book deal, but I don't feel deserving of it.

Image Credit: Pixelstalk Creative Commons

My ego is so huge it won't fit through the door.

I don't know how I feel about it. I should be excited. Many of you have this exact dream to publish a book with a well-known book publisher and get a juicy advance.

Let me dissect how I'm thinking about it to help you.

How it happened

An email comes in. A generic "can we put a backlink on your website and get a freebie" email.

Almost deleted it.

Then I noticed the logo. It seemed shady. I found the URL. Check. I searched the employee's LinkedIn. Legit. I avoided middlemen. Check.

Mixed feelings. LinkedIn hasn't valued my writing for years. I'm just a guy in an unironed t-shirt whose content they sell advertising against.

They get big dollars. I get $0 and a few likes, plus some email subscribers.

Still, I felt adrenaline for hours.

I texted a few friends to see how they felt. I wrapped them.

Messages like "No shocker. You're entertaining online." I didn't like praises, so I blushed.

The thrill faded after hours. Who knows?

Most authors desire this chance.

"You entitled piece of crap, Denning!"

You may think so. Okay. My job is to stand on the internet and get bananas thrown at me.

I approached writing backwards. More important than a book deal was a social media audience converted to an email list.

Romantic authors think backward. They hope a fantastic book will land them a deal and an audience.

Rarely occurs. So I never pursued it. It's like permission-seeking or the lottery.

Not being a professional writer, I've never written a good book. I post online for fun and to express my opinions.

Writing is therapeutic. I overcome mental illness and rebuilt my life this way. Without blogging, I'd be dead.

I've always dreamed of staying alive and doing something I love, not getting a book contract. Writing is my passion. I'm a winner without a book deal.

Why I was given a book deal

You may assume I received a book contract because of my views or follows. Nope.

They gave me a deal because they like my writing style. I've heard this for eight years.

Several authors agree. One asked me to improve their writer's voice.

Takeaway: highlight your writer's voice.

What if they discover I'm writing incompetently?

An edited book is published. It's edited.

I need to master writing mechanics, thus this concerns me. I need help with commas and sentence construction.

I must learn verb, noun, and adjective. Seriously.

Writing a book may reveal my imposter status to a famous publisher. Imagine the email

"It happened again. He doesn't even know how to spell. He thinks 'less' is the correct word, not 'fewer.' Are you sure we should publish his book?"

Fears stink.

Photo by Nathalia Segato on Unsplash

I'm capable of blogging. Even listicles. So what?

Writing for a major publisher feels advanced.

I only blog. I'm good at listicles. Digital media executives have criticized me for this.

  • It is allegedly clickbait.

  • Or it is following trends.

  • Alternately, growth hacking.

Never. I learned copywriting to improve my writing.

Apple, Amazon, and Tesla utilize copywriting to woo customers. Whoever thinks otherwise is the wisest person in the room.

Old-schoolers loathe copywriters.

Their novels sell nothing.

They assume their elitist version of writing is better and that the TikTok generation will invest time in random writing with no subheadings and massive walls of text they can't read on their phones.

I'm terrified of book proposals.

My friend's book proposal suggestion was contradictory and made no sense.

They told him to compose another genre. This book got three Amazon reviews. Is that a good model?

The process disappointed him. I've heard other book proposal horror stories. Tim Ferriss' book "The 4-Hour Workweek" was criticized.

Because he has thick skin, his book came out. He wouldn't be known without that.

I hate book proposals.

An ongoing commitment

Writing a book is time-consuming.

I appreciate time most. I want to focus on my daughter for the next few years. I can't recreate her childhood because of a book.

No idea how parents balance kids' goals.

My silly face in a bookstore. Really?

Genuine thought.

I don't want my face in bookstores. I fear fame. I prefer anonymity.

I want to purchase a property in a bad Australian area, then piss off and play drums. Is bookselling worth it?

Are there even bookstores anymore?

(Except for Ryan Holiday's legendary Painted Porch Bookshop in Texas.)

What's most important about books

Many were duped.

Tweets and TikTok hopscotch vids are their future. Short-form content creates devoted audiences that buy newsletter subscriptions.

Books=depth.

Depth wins (if you can get people to buy your book). Creating a book will strengthen my reader relationships.

It's cheaper than my classes, so more people can benefit from my life lessons.

A deeper justification for writing a book

Mind wandered.

If I write this book, my daughter will follow it. "Look what you can do, love, when you ignore critics."

That's my favorite.

I'll be her best leader and teacher. If her dad can accomplish this, she can too.

My kid can read my book when I'm gone to remember her loving father.

Last paragraph made me cry.

The positive

This book thing might make me sound like Karen.

The upside is... Building in public, like I have with online writing, attracts the right people.

Proof-of-work over proposals, beautiful words, or huge aspirations. If you want a book deal, try writing online instead of the old manner.

Next steps

No idea.

I'm a rural Aussie. Writing a book in the big city is intimidating. Will I do it? Lots to think about. Right now, some level of reflection and gratitude feels most appropriate.

Sometimes when you don't feel worthy, it gives you the greatest lessons. That's how I feel about getting offered this book deal.

Perhaps you can relate.

Scott Galloway

Scott Galloway

7 months ago

Don't underestimate the foolish

ZERO GRACE/ZERO MALICE

Big companies and wealthy people make stupid mistakes too.

Your ancestors kept snakes and drank bad water. You (probably) don't because you've learnt from their failures via instinct+, the ultimate life-lessons streaming network in your head. Instincts foretell the future. If you approach a lion, it'll eat you. Our society's nuanced/complex decisions have surpassed instinct. Human growth depends on how we handle these issues. 80% of people believe they are above-average drivers, yet few believe they make many incorrect mistakes that make them risky. Stupidity hurts others like death. Basic Laws of Human Stupidity by Carlo Cipollas:

  1. Everyone underestimates the prevalence of idiots in our society.

  2. Any other trait a person may have has no bearing on how likely they are to be stupid.

  3. A dumb individual is one who harms someone without benefiting themselves and may even lose money in the process.

  4. Non-dumb people frequently underestimate how destructively powerful stupid people can be.

  5. The most dangerous kind of person is a moron.

Professor Cippola defines stupid as bad for you and others. We underestimate the corporate world's and seemingly successful people's ability to make bad judgments that harm themselves and others. Success is an intoxication that makes you risk-aggressive and blurs your peripheral vision.

Stupid companies and decisions:

Big Dumber

Big-company bad ideas have more bulk and inertia. The world's most valuable company recently showed its board a VR headset. Jony Ive couldn't destroy Apple's terrible idea in 2015. Mr. Ive said that VR cut users off from the outer world, made them seem outdated, and lacked practical uses. Ives' design team doubted users would wear headsets for lengthy periods.

VR has cost tens of billions of dollars over a decade to prove nobody wants it. The next great SaaS startup will likely come from Florence, not Redmond or San Jose.

Apple Watch and Airpods have made the Cupertino company the world's largest jewelry maker. 10.5% of Apple's income, or $38 billion, comes from wearables in 2021. (seven times the revenue of Tiffany & Co.). Jewelry makes you more appealing and useful. Airpods and Apple Watch do both.

Headsets make you less beautiful and useful and promote isolation, loneliness, and unhappiness among American teenagers. My sons pretend they can't hear or see me when on their phones. VR headsets lack charisma.

Coinbase disclosed a plan to generate division and tension within its workplace weeks after Apple was pitched $2,000 smokes. The crypto-trading platform is piloting a program that rates staff after every interaction. If a coworker says anything you don't like, you should tell them how to improve. Everyone gets a 110-point scorecard. Coworkers should evaluate a person's rating while deciding whether to listen to them. It's ridiculous.

Organizations leverage our superpower of cooperation. This encourages non-cooperation, period. Bridgewater's founder Ray Dalio designed the approach to promote extreme transparency. Dalio has 223 billion reasons his managerial style works. There's reason to suppose only a small group of people, largely traders, will endure a granular scorecard. Bridgewater has 20% first-year turnover. Employees cry in bathrooms, and sex scandals are settled by ignoring individuals with poor believability levels. Coinbase might take solace that the stock is 80% below its initial offering price.

Poor Stupid

Fools' ledgers are valuable. More valuable are lists of foolish rich individuals.

Robinhood built a $8 billion corporation on financial ignorance. The firm's median account value is $240, and its stock has dropped 75% since last summer. Investors, customers, and society lose. Stupid. Luna published a comparable list on the blockchain, grew to $41 billion in market cap, then plummeted.

A podcast presenter is recruiting dentists and small-business owners to invest in Elon Musk's Twitter takeover. Investors pay a 7% fee and 10% of the upside for the chance to buy Twitter at a 35% premium to the current price. The proposal legitimizes CNBC's Trade Like Chuck advertising (Chuck made $4,600 into $460,000 in two years). This is stupid because it adds to the Twitter deal's desperation. Mr. Musk made an impression when he urged his lawyers to develop a legal rip-cord (There are bots on the platform!) to abandon the share purchase arrangement (for less than they are being marketed by the podcaster). Rolls-Royce may pay for this list of the dumb affluent because it includes potential Cullinan buyers.

Worst company? Flowcarbon, founded by WeWork founder Adam Neumann, operates at the convergence of carbon and crypto to democratize access to offsets and safeguard the earth's natural carbon sinks. Can I get an ayahuasca Big Gulp?

Neumann raised $70 million with their yogababble drink. More than half of the consideration came from selling GNT. Goddess Nature Token. I hope the company gets an S-1. Or I'll start a decentralized AI Meta Renewable NFTs company. My Community Based Ebitda coin will fund the company. Possible.

Stupidity inside oneself

This weekend, I was in NYC with my boys. My 14-year-old disappeared. He's realized I'm not cool and is mad I let the charade continue. When out with his dad, he likes to stroll home alone and depart before me. Friends told me hell would return, but I was surprised by how fast the eye roll came.

Not so with my 11-year-old. We went to The Edge, a Hudson Yards observation platform where you can see the city from 100 storeys up for $38. This is hell's seventh ring. Leaning into your boys' interests is key to engaging them (dad tip). Neither loves Crossfit, WW2 history, or antitrust law.

We take selfies on the Thrilling Glass Floor he spots. Dad, there's a bar! Coke? I nod, he rushes to the bar, stops, runs back for money, and sprints back. Sitting on stone seats, drinking Atlanta Champagne, he turns at me and asks, Isn't this amazing? I'll never reach paradise.

Later that night, the lads are asleep and I've had two Zacapas and Cokes. I SMS some friends about my day and how I feel about sons/fatherhood/etc. How I did. They responded and approached. The next morning, I'm sober, have distance from my son, and feel ashamed by my texts. Less likely to impulsively share my emotions with others. Stupid again.

Ashraful Islam

Ashraful Islam

1 year ago

Clean API Call With React Hooks

Photo by Juanjo Jaramillo on Unsplash

Calling APIs is the most common thing to do in any modern web application. When it comes to talking with an API then most of the time we need to do a lot of repetitive things like getting data from an API call, handling the success or error case, and so on.

When calling tens of hundreds of API calls we always have to do those tedious tasks. We can handle those things efficiently by putting a higher level of abstraction over those barebone API calls, whereas in some small applications, sometimes we don’t even care.

The problem comes when we start adding new features on top of the existing features without handling the API calls in an efficient and reusable manner. In that case for all of those API calls related repetitions, we end up with a lot of repetitive code across the whole application.

In React, we have different approaches for calling an API. Nowadays mostly we use React hooks. With React hooks, it’s possible to handle API calls in a very clean and consistent way throughout the application in spite of whatever the application size is. So let’s see how we can make a clean and reusable API calling layer using React hooks for a simple web application.

I’m using a code sandbox for this blog which you can get here.

import "./styles.css";
import React, { useEffect, useState } from "react";
import axios from "axios";

export default function App() {
  const [posts, setPosts] = useState(null);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    handlePosts();
  }, []);

  const handlePosts = async () => {
    setLoading(true);
    try {
      const result = await axios.get(
        "https://jsonplaceholder.typicode.com/posts"
      );
      setPosts(result.data);
    } catch (err) {
      setError(err.message || "Unexpected Error!");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="App">
      <div>
        <h1>Posts</h1>
        {loading && <p>Posts are loading!</p>}
        {error && <p>{error}</p>}
        <ul>
          {posts?.map((post) => (
            <li key={post.id}>{post.title}</li>
          ))}
        </ul>
      </div>
    </div>
  );
}

I know the example above isn’t the best code but at least it’s working and it’s valid code. I will try to improve that later. For now, we can just focus on the bare minimum things for calling an API.

Here, you can try to get posts data from JsonPlaceholer. Those are the most common steps we follow for calling an API like requesting data, handling loading, success, and error cases.

If we try to call another API from the same component then how that would gonna look? Let’s see.

500: Internal Server Error

Now it’s going insane! For calling two simple APIs we’ve done a lot of duplication. On a top-level view, the component is doing nothing but just making two GET requests and handling the success and error cases. For each request, it’s maintaining three states which will periodically increase later if we’ve more calls.

Let’s refactor to make the code more reusable with fewer repetitions.

Step 1: Create a Hook for the Redundant API Request Codes

Most of the repetitions we have done so far are about requesting data, handing the async things, handling errors, success, and loading states. How about encapsulating those things inside a hook?

The only unique things we are doing inside handleComments and handlePosts are calling different endpoints. The rest of the things are pretty much the same. So we can create a hook that will handle the redundant works for us and from outside we’ll let it know which API to call.

500: Internal Server Error

Here, this request function is identical to what we were doing on the handlePosts and handleComments. The only difference is, it’s calling an async function apiFunc which we will provide as a parameter with this hook. This apiFunc is the only independent thing among any of the API calls we need.

With hooks in action, let’s change our old codes in App component, like this:

500: Internal Server Error

How about the current code? Isn’t it beautiful without any repetitions and duplicate API call handling things?

Let’s continue our journey from the current code. We can make App component more elegant. Now it knows a lot of details about the underlying library for the API call. It shouldn’t know that. So, here’s the next step…

Step 2: One Component Should Take Just One Responsibility

Our App component knows too much about the API calling mechanism. Its responsibility should just request the data. How the data will be requested under the hood, it shouldn’t care about that.

We will extract the API client-related codes from the App component. Also, we will group all the API request-related codes based on the API resource. Now, this is our API client:

import axios from "axios";

const apiClient = axios.create({
  // Later read this URL from an environment variable
  baseURL: "https://jsonplaceholder.typicode.com"
});

export default apiClient;

All API calls for comments resource will be in the following file:

import client from "./client";

const getComments = () => client.get("/comments");

export default {
  getComments
};

All API calls for posts resource are placed in the following file:

import client from "./client";

const getPosts = () => client.get("/posts");

export default {
  getPosts
};

Finally, the App component looks like the following:

import "./styles.css";
import React, { useEffect } from "react";
import commentsApi from "./api/comments";
import postsApi from "./api/posts";
import useApi from "./hooks/useApi";

export default function App() {
  const getPostsApi = useApi(postsApi.getPosts);
  const getCommentsApi = useApi(commentsApi.getComments);

  useEffect(() => {
    getPostsApi.request();
    getCommentsApi.request();
  }, []);

  return (
    <div className="App">
      {/* Post List */}
      <div>
        <h1>Posts</h1>
        {getPostsApi.loading && <p>Posts are loading!</p>}
        {getPostsApi.error && <p>{getPostsApi.error}</p>}
        <ul>
          {getPostsApi.data?.map((post) => (
            <li key={post.id}>{post.title}</li>
          ))}
        </ul>
      </div>
      {/* Comment List */}
      <div>
        <h1>Comments</h1>
        {getCommentsApi.loading && <p>Comments are loading!</p>}
        {getCommentsApi.error && <p>{getCommentsApi.error}</p>}
        <ul>
          {getCommentsApi.data?.map((comment) => (
            <li key={comment.id}>{comment.name}</li>
          ))}
        </ul>
      </div>
    </div>
  );
}

Now it doesn’t know anything about how the APIs get called. Tomorrow if we want to change the API calling library from axios to fetch or anything else, our App component code will not get affected. We can just change the codes form client.js This is the beauty of abstraction.

Apart from the abstraction of API calls, Appcomponent isn’t right the place to show the list of the posts and comments. It’s a high-level component. It shouldn’t handle such low-level data interpolation things.

So we should move this data display-related things to another low-level component. Here I placed those directly in the App component just for the demonstration purpose and not to distract with component composition-related things.

Final Thoughts

The React library gives the flexibility for using any kind of third-party library based on the application’s needs. As it doesn’t have any predefined architecture so different teams/developers adopted different approaches to developing applications with React. There’s nothing good or bad. We choose the development practice based on our needs/choices. One thing that is there beyond any choices is writing clean and maintainable codes.