简体   繁体   中英

Where is the best place to put the javascript inside React?

I have 3 options. The difference is where my javascript code is located.

First (inside return):

export default function App() {

    return (
        <div>
            {/* Some javascript code */}
            <p>I am a paragraph</p>
        </div>
    )
}

Second (before return):

export default function App() {

    {/* Some javascript code */}

    return (
        <div>
            <p>I am a paragraph</p>
        </div>
    )
}

Third (inside useEffect):

import { useEffect } from "react";
export default function App() {  
    useEffect(() => {/* Some javascript code */}, [])
    return (
        <div>
            <p>I am a paragraph</p>
        </div>
    )
}

I do not know if this will change the answer, but my real javascript code is this:

//This is a simple code to display the window width
import { useState, useEffect } from "react";
export default function Example() {
    
    const [width, setWidth] = useState(window.innerWidth)

    useEffect(() => {
        window.addEventListener('resize', () => setWidth(window.innerWidth) )
    }, [])

    return <p>{width}</p>
}

The first (inside return ) and second (before return ) example have the same effect: the code runs on first render and every re-render .

In the third (inside useEffect ) example, the code only runs once on first render .

useEffect with empty dependency array acts similar to class-based component method componentDidMount .

If you need something like addEventListener or fetching data from outside API only for first render, it's a better idea to wrap them inside useEffect .

Options with useEffect is fine, just return unsubscribe function.

useEffect(() => {
    const resizeCb = () => setWidth(window.innerWidth)

    window.addEventListener('resize', resizeCb)

    return () => window.removeEventListener('resize', resizeCb)
}, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM