Friday, May 8, 2020

useEffect Hook example in React 16.8

In the previous post we saw an example of how to use the useState hook in a function component to maintain and update state props. In this post we will see an example on how to use the useEffect hook to perform side effects from a function component.

In this sample, we will use the useEffect hook to change the title of the document. We will use the value from the state prop title to set the document title as Hello + {title}. Initially the title will be displayed as Hello React, on clicking a button we change the state value of title, which in-turn triggers the useEffect and changes the document title.

import React, { useState, useEffect } from 'react';
import './App.css';

function UseEffectComponent() {
    const [title, setTitle] = useState('React');

    useEffect(() => {
        document.title = `Hello ${title}`;
      });
 
    return (
    <div className="App">
        <header className="App-header">
            <button onClick={() => setTitle('useEffect')}>
            Click to change Title
            </button>
        </header>
    </div>
    );
}

export default UseEffectComponent;

Build and run the application, notice the title of the document. Click the button and notice that the title gets updated using the useEffect hook.




Search Flipkart Products:
Flipkart.com

No comments: