React Hooks
React Hook is a simple JavaScript function that we can use to isolate the reusable part from a functional component. Hooks can be stateful and can manage side effects.
Key concepts to remember
- useState Hook:
The
useStatehook adds state functionality to components. It allows us to declare and manage state variables within a component. By calling theuseStatehook, we can initialize a state variable and its corresponding setter function. Updating the state variable triggers a re-render of the component, reflecting the new state value. - useRef Hook:
The
useRefhook creates mutable variables that persist across component renders. UnlikeuseState, changes touseRefvariables do not trigger a re-render.useRefaccess or store references to DOM elements, manage previous values, or preserve values between renders. - useEffect Hook:
The
useEffecthook enables us to perform side effects in functional components. It allows us to handle tasks like data fetching, subscriptions, or interacting with the DOM. By specifying dependencies, we control when the effect runs, optimizing performance and preventing unnecessary re-renders. - useMemo Hook:
The
useMemohook enables the memoization of expensive calculations or computations. It takes a function and a dependencies array and returns a memoized value. The memoized value is only recomputed by providing a dependencies array when the dependencies change. This optimization significantly improves performance by avoiding unnecessary recalculations.
Example
Let's create the component Counter to showcase how the useState hook is used for managing state and how the useEffect hook can be utilized to handle side effects and perform cleanup operations.
import React, { useState, useEffect } from "react";
const Counter = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Effect triggered!");
}, [count]);
const incrementCount = () => {
setCount((prevCount) => prevCount + 1);
};
return (
<div>
<h1>Count: {count}</h1>
<button onClick={incrementCount}>Increment</button>
</div>
);
};
export default Counter;
Code explanation:
- Line 1: We import the necessary dependencies from the React library. Specifically, we import the React object, the
useState, anduseEffecthooks. - Line 3: The code defines a React functional component named
Counter. - Line 4: We use the
useStatehook to declare a state variable calledcountand its corresponding setter functionsetCount. The initial value ofcountis set to0. - Line 6-8: We utilize the
useEffecthook to define a side effect. The effect function logs "Effect triggered!" to the console and will be triggered after every component render. The effect function has a dependency array[count], which means it will only run when thecountvalue changes. - Line 10-12: We declare an
incrementCountfunction to update thecountstate. It utilizes thesetCountsetter function provided by theuseStatehook. The function receives the previousprevCountvalue and returns the updated count by incrementing it by 1. - Line 14-19: Return HTML elements. Mainly,
h1displays the current value of thecountstate variable.buttonhasonClickevent handler that triggers theincrementCountfunction when clicked. - Line 22: The
Countercomponent is exported as thedefault export, allowing it to be imported and used in other application parts.
Complete code
Please, check the console to see the work of the useEffect hook.
Challenge
Let's create a component responsible for filtering a list of items. The component renders a list of items and allows users to type into an input element to filter the list. Only the items that contain the inputted symbols should be displayed.
The task is:
- Import the necessary hooks from the react library.
- Set the initial value for the input element correctly.
- Specify the correct values for the dependency array in the
useEffecthook.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Awesome!
Completion rate improved to 1.96
React Hooks
Stryg for at vise menuen
React Hook is a simple JavaScript function that we can use to isolate the reusable part from a functional component. Hooks can be stateful and can manage side effects.
Key concepts to remember
- useState Hook:
The
useStatehook adds state functionality to components. It allows us to declare and manage state variables within a component. By calling theuseStatehook, we can initialize a state variable and its corresponding setter function. Updating the state variable triggers a re-render of the component, reflecting the new state value. - useRef Hook:
The
useRefhook creates mutable variables that persist across component renders. UnlikeuseState, changes touseRefvariables do not trigger a re-render.useRefaccess or store references to DOM elements, manage previous values, or preserve values between renders. - useEffect Hook:
The
useEffecthook enables us to perform side effects in functional components. It allows us to handle tasks like data fetching, subscriptions, or interacting with the DOM. By specifying dependencies, we control when the effect runs, optimizing performance and preventing unnecessary re-renders. - useMemo Hook:
The
useMemohook enables the memoization of expensive calculations or computations. It takes a function and a dependencies array and returns a memoized value. The memoized value is only recomputed by providing a dependencies array when the dependencies change. This optimization significantly improves performance by avoiding unnecessary recalculations.
Example
Let's create the component Counter to showcase how the useState hook is used for managing state and how the useEffect hook can be utilized to handle side effects and perform cleanup operations.
import React, { useState, useEffect } from "react";
const Counter = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Effect triggered!");
}, [count]);
const incrementCount = () => {
setCount((prevCount) => prevCount + 1);
};
return (
<div>
<h1>Count: {count}</h1>
<button onClick={incrementCount}>Increment</button>
</div>
);
};
export default Counter;
Code explanation:
- Line 1: We import the necessary dependencies from the React library. Specifically, we import the React object, the
useState, anduseEffecthooks. - Line 3: The code defines a React functional component named
Counter. - Line 4: We use the
useStatehook to declare a state variable calledcountand its corresponding setter functionsetCount. The initial value ofcountis set to0. - Line 6-8: We utilize the
useEffecthook to define a side effect. The effect function logs "Effect triggered!" to the console and will be triggered after every component render. The effect function has a dependency array[count], which means it will only run when thecountvalue changes. - Line 10-12: We declare an
incrementCountfunction to update thecountstate. It utilizes thesetCountsetter function provided by theuseStatehook. The function receives the previousprevCountvalue and returns the updated count by incrementing it by 1. - Line 14-19: Return HTML elements. Mainly,
h1displays the current value of thecountstate variable.buttonhasonClickevent handler that triggers theincrementCountfunction when clicked. - Line 22: The
Countercomponent is exported as thedefault export, allowing it to be imported and used in other application parts.
Complete code
Please, check the console to see the work of the useEffect hook.
Challenge
Let's create a component responsible for filtering a list of items. The component renders a list of items and allows users to type into an input element to filter the list. Only the items that contain the inputted symbols should be displayed.
The task is:
- Import the necessary hooks from the react library.
- Set the initial value for the input element correctly.
- Specify the correct values for the dependency array in the
useEffecthook.
Tak for dine kommentarer!