V
V
Vadim Stepanenko2021-03-16 15:33:17
React
Vadim Stepanenko, 2021-03-16 15:33:17

How can this component be optimized?

Hey! Just started learning hooks so please don't throw rocks.

Actually, there is a component that should output N times another component.
N is the height of the screen / the height of the repeating component.

Implemented like this:

const Repeater = () => {
    const items = Math.ceil(window.screen.height / 130);

    return (
        <div className="list">
            {[...Array(items)].map((value, index) => (
                <RepeatedComponent />
            ))}
        </div>
    );
};

export default Repeater ;


There is very little code, so there are several questions:
1. You can calculate const items = Math.ceil(window.screen.height / 130); So? Or should I wrap it in something? (as an option to use the useState hook, and calculate in useEffect?)
2. [...Array(items)].map((value, index) isn't bad practice? It's the shortest implementation I could think of

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
davidnum95, 2021-03-16
@Vadim1899

Can it be like this

const Repeater = () => {
    const items = useMemo(() => {
    	const itemsCount = Math.ceil(window.screen.height / 130);
    	return Array.from(Array(itemsCount).keys())
    }, [window.screen.height])

    return (
        <div className="list">
            {items.map((value, index) => (
                <RepeatedComponent key={value} />
            ))}
        </div>
    );
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question