What's Hooks?: Declaring State Variable

Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 8

What’s Hooks?

Hooks are new to React. They are first represented in february 2019, the release date of the 16.8
version.
Hooks are a set of functions that allow us all the benefits of a JavaScript class (like state, and life
cycle methods) combine with the flexibility of functional programming. In other words, hook allow
us to use only function in the whole application without the need to implement classes.
React provides some predefined Hooks like useState, useEffect, useRef. You can also create your
own hooks to reuse stateful behavior in different components.

useState
While describing the use of the state in the previous super skill, we have seen that the state can only
be updated using the this.setState method.
The state is characterized by two major thing a value (aka getter) and a method to set this value
(aka setter).

The same logic still valid with the useState() method.

Declaring state variable:


First of all, we need to learn how to declare a state variable in our component:
1. Import the hook useState
2. Declare your state variable in an array (the getter and the setter)
3. Initialize your state variable with useState( ).
This example will help you to understand :
import React, { useState } from "react";
Access the state
Now that we have already declared our component state, we need to be able to access the value of
that state.
Like any other variable in JavaScript, if we want the value of a state we only invoke the state’s
name, like shown in the example below
import React, { useState } from "react";

const MyFunctionComponent = props => {


// setting the state hooks
const [name, setName] = useState("Arya Stark");
return (
<div>
{/* here we use the getter to get the state value */}
<p>hello my name is {name}</p>
</div>
);
};

Set the state value:


To change the value of the state we have to use the setter that we implemented in the state
declaration, in this example the setter (or the modifier) is the setName method
const MyFunctionComponent = props => {
// declaring the state hooks
const [name, setName] = useState("Arya Stark");
// here we use the setter to change the content of the name state
const handleClick = () => setName('Tyron Lanyster')
return (
<div>
{/* here we use the getter to get the state value */}
<p>hello my name is {name}</p>
<button onClick={handleClick}>Click if you want to give the crown to Tyron
Lanyster</button>
</div>
);
};

What we should remember?


The useState() method is the one responsible to handle the state in a functional component.
Here what to keep in mind:
1. We should import useState from the react library
2. The value we include in the initial state is the value of the state until we change it.
We previously went over the functionality useState.
Actually, we will analyze more details about this method:
The useState will return an array [ ] with two elements :

1. The value that we have initialized


2. The function that will mutate the value of the state.
// In this case the useState will return an array where the name is "John Snow"
and setName
const [name, setName] = useState("John Snow ");

In this case, counter is :getter

const [counter,setCounter] = useState(0);

What is the initial value of the state ?5


const [counter,setCounter] = useState(5)

the setter is:a function that changes the value of the state variable

useEffect
The useEffect() method takes:
A function as the first parameter that describes the effect we want to apply. An array as a second
parameter that will define when this effect should appear or disappear.
So keep in mind that to start up, we need to use an empty array [ ] as a second parameter. But this
parameter remains optional.
[] means the effect doesn’t use any value that participates in React data flow, and is for that reason
safe to apply once.
It is also a common source of bugs when the value actually is used.
This code will clarify for you :
// setting the useEffect to trigger while the component is been rendering
useEffect(()=>{
alert(`hello this a message`)
},[])

useEffect
The useEffect() method allows component functions to manage side effects.
It plays the same role as componentDidMount(), componentDidUpdate(), and
componentWillUnmount() in React classes, but through a single API.

When the component execute useEffect?in every state modification


Will it work if we remove [ ] argument from useEffect?
True
In order to use a spinner, what should we add as a secondary parameter inside the useEffect
method ?[ ]

useRef()
The useRef() Hook is a function that returns a mutable reference object whose current property
is initialized to the passed argument (initialValue). The returned object will persist for the full
lifetime of the component.
This example may help you :
function App() {
let [name, setName] = useState("Ned stark");
// we declare the input inside the variable
let nameRef = useRef();
// we are referring to input to change the value
const submitButton = () => {
setName(nameRef.current.value);
};

return (
<div className="App">
<p>{name}</p>
<h1>Who is your favorite Games of throne character</h1>

<div>
<input
placehoder="enter your preferred GOT character..."
ref={nameRef}
type="text"
/>
<button type="button" onClick={submitButton}>
Submit
</button>
</div>
</div>
);
}

In this function we are recovering the input value using the useRef method instead of onChange
event. That may be a potential bug event if works for now. A ref created with useRef will be created
only when the component has been mounted. Refs can be used for accessing DOM nodes or React
elements, and for keeping mutable variables.

Destructuring using object:


Don't forget: hooks use Array to store data.
As we previously mentioned, Hooks is applied in an array:
const { state, setState} = useState("intial state")
If we perform a distructuring using the curly brackets we’ll have this error

Reminder this code is incorrect. We need to use bracket an not curly braces
const [state, setState] = useState("intialState)

Hooks inside a condition:


We should avoid : create the state hook in a condition that will violate the hooks rules. will violate
the hooks rules and this error will occur.
import React, { useState } from 'react'

const Welcome = props =>{


if(props.name==='ned stark'){
const [bgColor,setBgColor ]= useState('white')
}
else{
const [bgColor, setBgColor] = useState('black')
}

return (
<h1 style={{backgroundColor:{bgColor}}} >{props.name}</h1>
)
}

export default Welcome

Hooks inside a loop:


Another common mistake is to use the hook inside loops. Here is an example to illustrate the error.
function App() {
for (let i = 1; i < 5; i++) {
const [state, setstate] = useState(i);
}
return (
<div>
<h1>{state}</h1>
</div>
);
}

export default App;

Nesting before using the state:


We can't nest inside function before using our State
function App({ date }) {
function updateCount(byValue) {
const [currentDate, setCurrentDate] = useState(new Date());
const [count, setCount] = useState(0);
setCount(count + byValue);
setCurrentDate(new Date());
}

function formatDate() {
const hour = currentDate.getHours();
const minute = currentDate.getMinutes();
const second = currentDate.getSeconds();

return `${hour}:${minute}:${second}`;
}

const prettyDate = formatDate();

return (
<div className="App">
<h2>
You clicked {count} times, last time at {prettyDate}!
</h2>

<button onClick={() => updateCount(-1)}>Decrement</button>


<button onClick={() => updateCount(1)}>Increment</button>
</div>
);
}

useState insinde an effect:


Now, we will go through some points went invoke the useEffect.
the usage of useState inside useEffect. In fact this combination will generate an infinite
loop.
So don't call a useState inside a useEffect

Let's recap:
To summarize, we can only call Hooks at the top level.
We should be aware of these rules:
• Don't declare hooks in if statements.
• Don't declare hooks in loops.
• Don't declare hooks in nested function.
• Keep in mind to pay attention to the usage of the brackets instead of the curly brackets.
The following code is it correct:False
const {name, setName}= useState()

We can't apply useEffect in :


In side a useState
in a condition (if/else statement)in a sub-funciton

We can invoke a useState() in a useeffect() hookFalse

Custom hooks
A custom hook is a JavaScript function Which name begins with "use". It provide a flexible logic
sharing.
We can call other Hooks in our custom Hooks.
Before we start, We need to be able to build our Hooks in a personalized way and it will still ensure
the functional reusability.
The example of a user and posts will help us to better understand custom hooks utility.

Custom hooks
Custom hooks are simply a wrapper function surrounding our existing hooks.
That's it! The only catch is that in order for React to recognize that a function is a custom hook, its
name must start with use, we will more details in next slides.
Note: The same rules are also applied to custom hooks.

Create custom hook


We will create a useInterval Hook and then we well use it
function useInterval (timeout, getValue) {
const [value, setValue] = useState(getValue);
useEffect(() => {
const intervalID = setInterval(
() => setValue(getValue()),
timeout
);
return function () {
clearInterval(intervalId);
}
}, []);
return value;
}
const get CurrentDate = () => new Date();
function App() {
const date = useInterval(1000, getCurrentDate);
return <p>Nous sommes le {date.toLocaleString(“fr-FR”)}</p>;
}

A custom hook is a JavaScript functionTrue


We can invoke a custom hook in a conditional statementFalse
A custom hook is function that provide a flexible code
True

Tips:
• Avoid declaring useState, useEffect or custom hook:
• In a loop
• In a condition
• In nested function
• Don't forget array destructuring.
• You should use custom hook with component that have the same functionality.
• Avoid applying useRef to any element of the DOM.

Let’s recap:
Hooks is a new feature that is introduced to React to make easier dynamic data manipulation.
useState is essential to select a default value for the state then updating it.
Time to apply what we have been leaning !

You might also like