What is the best way to add the same code to every component in React?

Viewed 45

I am trying to build a simple page navigation loading screen while using react-router-dom. My first instinct to start is to do something like:

export default function PageOne = () => {
    
    const [show, setShow] = useState('show');

    useEffect(() => {
        setTimeout(() => {
            setShow('');
        }, 500)
    }, [])    

    return (
        <>
            <div className={`loader ${show}`}></div>
            <div className="PageOne">
                Here is my content for page one
            </div>
        </>
    )
}

Here, the loader div would be displayed with a position: absolute, height: 100vh, and width: 100vw. Then after 500ms, it can be animated to fade out or slide off screen.

This doesn't feel like a great solution, and it means that the same code will be rewritten within every single page. Is there a simpler or more 'reacty' way to do this?

1 Answers

Yes, you have the right thinking. To be honest, React is all about code sharing. You can share functions, components, hooks, contexts, etc. There's no right or wrong what you want to share, however if you just want to extract couple of your lines involving useState etc, you can use a hook.

  const useMyOwnHook = () => { 
    const [show, setShow] = useState('show');

    useEffect(() => {
        setTimeout(() => {
            setShow('');
        }, 500)
    }, [])    

    return show
  }

Then you can use it as

export default function PageOne = () => {
    
    const show = useMyOwnHook() 

    return (
        <>
            <div className={`loader ${show}`}></div>
            <div className="PageOne">
                Here is my content for page one
            </div>
        </>
    )
}

By the way, don't ask me what your code means. I'm only refactor your code, and that is what a hook is about.

Related