What's Hooks?: Declaring State Variable
What's Hooks?: Declaring State Variable
What's Hooks?: Declaring State Variable
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 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.
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.
Reminder this code is incorrect. We need to use bracket an not curly braces
const [state, setState] = useState("intialState)
return (
<h1 style={{backgroundColor:{bgColor}}} >{props.name}</h1>
)
}
function formatDate() {
const hour = currentDate.getHours();
const minute = currentDate.getMinutes();
const second = currentDate.getSeconds();
return `${hour}:${minute}:${second}`;
}
return (
<div className="App">
<h2>
You clicked {count} times, last time at {prettyDate}!
</h2>
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()
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.
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 !