• Home
  • React
  • React Hooks – useEffect hook example

React Hooks – useEffect hook example



UseEffect hook runs after first render and after every other completed render (but we can change that, so it can runs after first render and only when certain values have changed). We may put in it piece of code, that runs after component render, so we can change state or manipulate DOM tree before it will display on screen).

Basically, we can use useEffect hook in two main situations:

  1. To the effect, that don’t require cleanup (logging, network requests or manual DOM mutations).
  2. To the effect, that require cleanup (e.g clearing setTimeout function)


Effects, that don’t require cleanup

This kind of effects don’t need to be cleanup, so we can set them and forget about them. For example, we can dynamically set title of our document:

const HookExample = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `Clicked ${count} times`;
  });
}


Whatever we put inside useEffect function, it will be rendered every time, when component is rendered. However, we can limit numer of renders and call useEffect function only when certain values have changed, by passing array od dependencies. If array is empty, useEffect function will run only one time, after first render.

const HookExample = (props) => {    
    const [points, setPoints] = useState(0);

    useEffect(() => {
        // this will display only if state points will change
        console.log("state changed");
    },[points]);

    useEffect(() => {
        // this will display only if props points will change
        console.log("props changed");
    },[props.points]);

    useEffect(() => {
        // this will display only one time, with first render
        console.log("one time display");
    },[]);

    return (
        ...
    );
}


Effects, that require cleanup

Some effects require cleanup (e.g. to avoid memory leak). In this case we can return cleanup function inside useEffect function:

const HookExample = (props) => {    
    const [points, setPoints] = useState(0);

    useEffect(() => {
        // this will display only one time, before the component is removed from the UI, and its called "clean-up function"

        return () => {
            console.log("component unmount");
        } 
    },[]);

    return (
        ...
    );
}

export default HookExample;


Click on DEMO to see how useMemo hook works

You can find this code in repo: https://github.com/love-coding-pl/React-Hooks-Examples/tree/Hook-4-useEffect

Joanna

Leave a Reply

Your email address will not be published. Required fields are marked *