0% found this document useful (0 votes)
40 views19 pages

Ces Idées Qui Collent

The document discusses React hooks, which are functions that allow building React components using only functions instead of classes. It covers the useState and useEffect hooks for managing state and side effects, and how to build custom hooks to extract reusable logic.

Uploaded by

Emna Ghariani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views19 pages

Ces Idées Qui Collent

The document discusses React hooks, which are functions that allow building React components using only functions instead of classes. It covers the useState and useEffect hooks for managing state and side effects, and how to build custom hooks to extract reusable logic.

Uploaded by

Emna Ghariani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

HOOKS in REACT

The answer to the big question:

"What the heck are hooks?"


Introduction
REACT HOOKS (introduced in React since version 16.8) are
JavaScript functions that allow us to build our React
component ONLY with function.
It’s main purpose is to solve some of the complications
associated with the class logic.
React provides a few Hooks to manage most of the use cases
of the class logic. It also came up with a better way to create
custom Hooks whenever we want to reuse stateful logic
between components.
Lets focus on the following 2 React

Hooks:

● 📌 State Hook — useState

● ⚡ Effect Hook — useEffect

and the ⭕ Custom hooks !


📌 State Hook — useState
useState allows us to make our components stateful. We call it inside a function component
to add some local state to it:

● The only argument passed to useState is the initial state.

● useState hooks maintain state by being fed the latest state in a new every render.

● useState returns a tuple pair: the current state value and a function that lets you

update the state.

● You can have as many hooks in a function you can possibly want; so multiple pieces

of state each with their own updater function.


import React, { useState } from 'react';

function CounterWithHooks(props) {

const [count, setCount] = useState(props.initialValue);

return (

<div>

<h2>This is a counter using hooks</h2>

<h1>{count}</h1>

<button onClick={() => setCount(count + 1)}>Click to Increment</button>

</div>

);}

export default CounterWithHooks;


⚡ Effect Hook — useEffect
The Effect Hook, useEffect, adds the ability to perform side effects from a function
component. It serves the same purpose as componentDidMount, componentDidUpdate, and
componentWillUnmount in React classes, but unified into a single API.

When you call useEffect, you’re telling React to run your “effect” function after flushing
changes to the DOM. Effects are declared inside the component so they have access to its
props and state. By default, React runs the effects after every render — including the first
render.

The useEffect hook takes a second parameter, an array, containing the list of things that will
cause the useEffect hook to run. When changed, it will trigger the effect hook. So, whenever
your component receives a new prop from its parent, the useEffect hook will be triggered, and
the code within it will run.
import React, { useState } from 'react';

function CounterWithHooks(props) {

const [count, setCount] = useState(props.initialValue);


The document
useEffect(() => { document.title = `You clicked ${count} times`; },[]); title is updated
with a custom
return ( message
displaying the
<div> number of clicks!

<h2>This is a counter using hooks</h2>

<h1>{count}</h1>

<button onClick={() => setCount(count + 1)}>Click to Increment</button>

</div>

);}

export default CounterWithHooks;


⭕ Custom hooks
Custom React hooks are an essential tool that let you add special, unique
functionality to your React applications. It allows you to extract some
components logic into a reusable function.

A custom hook is a Javascript function that starts with use and that call
can other hooks.

Remember that components and hooks are functions, so we are really not
creating any new concepts here. We are just refactoring our code into
another function to make it reusable.
import React, { useState } from 'react';
import { useState, useMemo } from "react";

Use the hook useToggle in the component


const useToggle = () => {

const [state, setState] = useState("off");

const handlers = useMemo(() => ({ toggle: () => { setState((res) => (res === "on" ? "off" : "on")) ;} }),

[ ] );

return [state, handlers]; };


By using useMemo
export default useToggle; we are making
sure our function
remembers the
result of the last
now just import useToggle to the App.js time it was
called.
Now that we’ve learned what is

the react hooks are,

let’s look at 4 common

examples you’ll need to know

when using the useState hook!


Don’t worry, it ‘ll
be quick!
1. showing & hiding things
These include :

● Showing and hiding a modal


● Showing a loading spinner
● Toggling the display of a component

let’s look at an exemple where if the user


clicks a button, the text will appear on the
page:
import React, { useState } from 'react';

export default function App() {

const [showText, setShowText] = useState(false);

return (

<div className='App'>

<button onClick={() => setShowText(!showText)}>Toggle Text</button>

{showText && <div>This text will show!</div>}

</div> );}
2. Conditional Rendering

Similar to showing and hiding things, we


can conditionally render based on a state
value.

Lets take the example of a logged in user.


If a user goes to our app who isn’t logged in,
we want to show them the “Sign in” screen.
If they are logged in, we want to show them
the “Dashboard”
import React, { useState } from 'react';

function SignInScreen() {

return <div>Please login!</div>; }

function DashboardScreen() { This means “if


logged in is true,
show the
return <div>Hello! Welcome to your dashboard</div>; } DashboardScreen
component.

export default function App() {


Else, show the
SignInScreen
component.
const [ isLoggedIn, setIsLoggedIn ] = useState(false);

return <div className='App'> { isLoggedIn ? <DashboardScreen /> : <SignInScreen /> }</div>; }


3. Holding a list of data
Quite often you’ll need to display a list of
data in your app (did someone say TODO
LIST?). To do this, you can store the list in
state, and render each item in the list as a
component:
import React, { useState } from 'react';

export default function App() {

const [todos, setTodos] = useState([

{ description: 'First thing on the list', isComplete: false },

{ description: 'Second thing on the list', isComplete: false },

{ description: 'Last thing todo', isComplete: false }, ]);

return (<> {todos.map((todo) => (

<div> Description: {todo.description} - Completed: {todo.isComplete.toString()}</div>


))} </> ); }
4. Holding form values
Working with forms can be a pain, luckily
for us using React hooks makes it easier.
Let’s say we have a simple login form, when
the user logs in and alert pops up showing
the information they enter.
import React, { useState } from 'react';

export default function App() { Our form has 2 values,


each of which has their
own state value.
Whenever the user
const [username, setUsername] = useState(""); types into a form field,
we change the state
value for that form field.
const [password, setPassword] = useState("");

const handleFormSubmit = () => {alert(`username is ${username}, password is ${password}`);};

return ( <> <form onSubmit={handleFormSubmit}>

Username: <input value={username} onChange={(e) => setUsername(e.target.value)} />

Password: <input value={password} onChange={(e) => setPassword(e.target.value)} />

<button type='submit'>Submit</button> </form> </> ); }


Thank you for the attention!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy