What is hook?
-
Hooks allow function components to have access to state and other React features(eg: lifecycle methods).
Because of this, class components are generally no longer needed.
Conditions for hooks
Can only be called inside React function components
Must be called at the top level of a component
Cannot be used conditionally
Types of hooks
useState hook
-
Usage involves declaring a state variable, and when variable is updated react will trigger a re-render.
|
![]() 1. Creates a state variable color initially set to 'red'. setColor() is a function to update the color state variable When setColor() is called, React automatically re-renders the component 2. Button, onclick of button setColor() function is called, which updates the state variable 3. As state variable is called, React re-renders and background color changes to blue. |
useEffect hook
-
What is side effect in React
In React side effect is action or operation that occurs in a component after rendering, but is not directly related to rendering the user interface.
Examples of side effects:
Making an asynchronous request to fetch data from an API
Changing the title of a webpage
Setting up a subscription to an external data source
Keeping user information
Updating themes
useEffect manages side effects in components.
|
Output { "title":"The Basics - Networking", "description":"Your app fetched this from a remote endpoint!", "movies": [ {"id":"1","title":"Star Wars","releaseYear":"1977"}, {"id":"2","title":"Back to the Future","releaseYear":"1985"}, {"id":"3","title":"The Matrix","releaseYear":"1999"}, {"id":"4","title":"Inception","releaseYear":"2010"}, {"id":"5","title":"Interstellar","releaseYear":"2014"} ] } 1. Hooks useEffect, useState used 2. Local variable data is created 3. Inside useEffect() hook HTTP GET(fetch()) is called, on response response data is set a. empty dependency array [] ensures, fetch runs only once 4. .then statements: 1st then(parses response): response is the raw HTTP response object, response.json() converts the response body to a JSON object 2nd then(update component state): result is the parsed JSON data from the previous step, setData(result) updates the component's state with the fetched data Code without useEffect() = endless re-render
if fetch() is called without useEffect() following will happen:fetch() is called > setData() updates data variable > This triggers another component render > fetch() runs again > Creates an endless cycle of re-renders |