DEV Community

Cicada0315
Cicada0315

Posted on • Updated on

Hooks For Beginner

What is Hooks?

Hooks are a new addition in React 16.8. They are JavaScript functions that let you use state and other React features without writing a class (Hooks don’t work inside classes).

State Hook ('useState')

'useState' enables you to add state to functional components. We call this Hook inside a functional component to add some local state to it. React will preserve this state between re-renders.

const [state, setState] = useState(initialState);
Enter fullscreen mode Exit fullscreen mode

Returns a stateful value(state), and a function(setState) to update it.

Example

In this example, we are making total state. It is initialize as 0. Whenever you click the Button then the total state will increment by 1 and page will re-render with updated total state.

import React, { useState } from 'react';

function Example() {
  const [total, setTotal] = useState(0);
  return (
    <div>
      <h1>clicked {total} times</h1>
      <button onClick={() => setTotal(count + 1)}>Button</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Using class: Equivalent with above code

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      total: 0
    };
  }

  render() {
    return (
      <div>
        <h1>clicked {this.state.total} times</h1>
        <button onClick={() => this.setState(previousState => ({ total: previousState.total + 1 }))>
          Button
        </button>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

You can also use the State Hook more than once in a single component and the state can be any type unlike state in a class which is always be an object like example below:

function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [vegetable, setVegetable] = useState('onion');
  const [users, setUsers] = useState([{ Name: 'Jean' }]);
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Effect Hook ('useEffect')

Effect Hook serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API(simply working as all three combined). The function passed to useEffect will be called(run) after the render is committed to the screen. In other words, by using this Hook, you tell React that your component needs to do something after render.

With one parameter

useEffect(didUpdate);
Enter fullscreen mode Exit fullscreen mode

Example

import React, { useState, useEffect } from 'react';
function Example() {
  const [total, setTotal] = useState(0);

  // Similar to componentDidMount and componentDidUpdate: 
  // Update the document title using the browser API   
useEffect(() => {document.title = `clicked ${total} times`;});
  return (
    <div>
      <h1>clicked {total} times</h1>
      <button onClick={() => setTotal(total + 1)}>
        Button
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In here userEffect is working as componentDidMount and componentDidUpdate combined as explained in the code above.

With two parameters

useEffect(didUpdate, [dependency array]);
Enter fullscreen mode Exit fullscreen mode

with one paremeter, useEffect run after every render which means it runs both after the first render and after every update.

what if we want call this function when only certain value changes(update)? That is why we need second parameter which called as dependency array.
Dependency array is the second optional parameters in the useEffect function. The Effect will only executed when the second parameter value of array updated and inside the array we can put more then one value.

Example

const App=()=>{
  const [value, handleChange] = useFrom({ email: "", password: ""});
  useEffect(()=>{
    console.log("render");
  }, [values.password]);

  return(
    <div>
    <>
      <input name="email" value={values.email} onChange={handleChange}/>
      <input type="password" name="password" value={values.password} onChange={handleChange} />
    </>
    </div>
   );
};
Enter fullscreen mode Exit fullscreen mode

So whenever {values.password} changes then the Effect fires off again and again.

If you put second parameter as empty array [], it only implement componentDidMount not componentDidUpdate. So, it not doing to evoke when there any is changes. In other words, re-render is not going to call the Effect anymore and render only when component Mount.

useEffect(()=>{
    console.log("render");
  }, []);
Enter fullscreen mode Exit fullscreen mode

Effect Hook with cleanup

Simply put return function inside userEffect will performs the cleanup when the component unmount which is similar to componentWillUnmount.

useEffect(()=>{
    console.log("render");

    return ()=>{
      console.log("unmount");
    }
  }, []);
Enter fullscreen mode Exit fullscreen mode

If we user second parameter for some value like previous example. then we can cleaning up the old value and getting new value.

useEffect(()=>{
    console.log("render");

    return ()=>{
      console.log("unmount");
    }
}, [values.password]);
Enter fullscreen mode Exit fullscreen mode

We can have more then one useEffect in one component and it fired in order.

Keep in mind!

  1. Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
  2. Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions. (There is just one other valid place to call Hooks)

If you are still confused leave a comment or recommend to watch youtube link that I put in below.

reference:

https://reactjs.org/docs/hooks-overview.html
https://www.youtube.com/watch?v=j1ZRyw7OtZs

Top comments (0)