DEV Community

Tinkerjoe-Git
Tinkerjoe-Git

Posted on

Hooks at a Glance

So, What're 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). Other than that, there's little to no disadvantage.

Hook ('useState')

I mentioned we can use state, well '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

This'll return a stateful value, and a function(setState) for updating. For example.

import React, { useState } from 'react';

function Example() {
  const [total, setTotal] = useState(0);
  return (

      <h1>clicked {total} times</h1>
<pre class="highlight plaintext"><code>  &lt;button onClick={() =&gt; setTotal(count + 1)}&gt;Button&lt;/button&gt;
&lt;/div&gt;
</code></pre>
<p>);<br>
}</p>
<pre class="highlight plaintext"><code>


&lt;p&gt;You can hook it up as many times as you want in the same function. &lt;/p&gt;



</code></pre>
<p>function ExampleWithManyStates() {<br>
  // Declare multiple state variables!<br>
  const [age, setAge] = useState(42);<br>
  const [fruit, setFruit] = useState('banana');<br>
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);<br>
  //<br>
}</p>
<pre class="highlight plaintext"><code>

&lt;p&gt; Looking at the equivalent for class component would just take up a lot of space, you get it.&lt;/p&gt;

##* Hook ('useEffect')

&lt;p&gt; 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.&lt;/p&gt;



</code></pre>
<p>import React, { useState, useEffect } from 'react';<br>
function Example() {<br>
  const [total, setTotal] = useState(0);</p>

<p>// Similar to componentDidMount and componentDidUpdate: <br>
  // Update the document title using the browser API<br><br>
useEffect(() =&gt; {document.title = <code>clicked ${total} times</code>;});<br>
  return (<br>
    </p><br>
      <h1>clicked {total} times</h1><br>
      <button> setTotal(total + 1)}&gt;<br>
        Button<br>
      </button><br>
    <br>
  );<br>
}
<pre class="highlight plaintext"><code>

&lt;p&gt; So you can see, we're hitting more than a few birds with this Hookstone if you will, even if you wont...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.



</code></pre>
<p>const App=()=&gt;{<br>
  const [value, handleChange] = useFrom({ email: "", password: ""});<br>
  useEffect(()=&gt;{<br>
    console.log("render");<br>
  }, [values.password]);</p>

<p>return(<br>
    </p><br>
    &lt;&gt;<br>
      <br>
      <br>
    &lt;/&gt;<br>
    <br>
   );<br>
};
<pre class="highlight plaintext"><code>

&lt;p&gt; So whenever {values.password} changes then the Effect fires off again and again.

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

##Effect Hook cleanup on isle...your code
Simply put return function inside userEffect will performs the cleanup when the component unmount which is similar to componentWillUnmount.



</code></pre>
<p>useEffect(()=&gt;{<br>
    console.log("render");</p>
<pre class="highlight plaintext"><code>return ()=&gt;{
  console.log("unmount");
}
</code></pre>
<p>}, []);</p>
<pre class="highlight plaintext"><code>

Remember to clear up the old value before you try and get a new one.

##Lastly
Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions, it won't work out.



























</code></pre>
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)