DEV Community

Joshua Byrd
Joshua Byrd

Posted on

React Hooks explained as simply as I humanly can

Hooks let you do more things with function components.


You can use state with the useState() hook.

eg. const [count, setCount] = useState(0).

Now count equals 0.

Update count with setCount(1).

Now count equals 1 and the component will update.


You can also trigger side effects with the useEffect() hook.

eg. useEffect(() => console.log(count), [count]).

Now it will console log every time count updates.

hint: use [] to only trigger the side effect once when the component is mounted and just leave off the second argument to trigger the effect after any state change.

hint 2: if you return a function from your side effect it will run that function after the componet unmounts.


Here's some code.

import React, {useState, useEffect} from "react";

function Counter(props) {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = count;
  }, [count]);

  function countHigher() {
    setCount(count + 1);
  }

  return (
    <p onClick={countHigher}>
      {count}
    </p>
  );
}

Enter fullscreen mode Exit fullscreen mode

And that's pretty much it.

If you want a more in-depth look read the docs.

Top comments (8)

Collapse
 
huyduy profile image
Huy Duy

I just start learning React, I don't know if Hooks is a really important part to learn or not 😶

Collapse
 
kayis profile image
K

Depends on why you learn it.

If you have to maintain an older project, then I think hooks aren't important to get started.

If you start a new project, it could be wise to build it with hooks right away.

Collapse
 
httpjunkie profile image
Eric Bishard

Amen my brother!

Collapse
 
akado117 profile image
Alex

As someone who has used React for years. Hooks make your code more modular and reusable. It also removes a ton of boiler plate. If you're learning right now. It's probably best to keep with hooks. Then learn the old school way and compare how you feel with either.

Collapse
 
qzsg profile image
Adrian

Its even better to learn Hooks if u are starting from the beginning

Collapse
 
arswaw profile image
Arswaw

I'd like to rebuild my personal website in React. Maybe hooks will be useful.

Collapse
 
scriptkavi profile image
ScriptKavi

Many early birds have already started using this custom hooks library
in their ReactJs/NextJs project.

Have you started using it?

scriptkavi/hooks

PS: Don't be a late bloomer :P

Collapse
 
httpjunkie profile image
Eric Bishard • Edited

Check out my stuff, would love feedback...
React Hooks Writings and Presentations