loading...

React Hooks explained as simply as I humanly can

phocks profile image Joshua Byrd ・1 min read

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>
  );
}

And that's pretty much it.

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

Posted on by:

Discussion

markdown guide
 

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

 

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.

 
 

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.

 

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

 

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