user6329530
user6329530

Reputation: 734

How do I prevent a component from rendering twice?

I want to initialize a component but it keeps rendering all the time.

According to the documentation I use React.memo but that doesn't prevent the component from rerendering: console.log("re-render") prints more than once. How do I make that component exactly static no matter what happens above in the tree?

const Canvas = React.memo((props) => {
    const context = useContext(Context);
    const width = "500%";
    const height = "500%";

    const count = useRef(0);

    useEffect(() => {
        context.initCanvas("c");
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []); //runs only once on mount

    console.log("re-render"); //outputs all the time when I cange something above in the tree.

    return (
        <>
            <canvas
                style={{border: "1px dashed black", margin: "10px"}}
                id="c"
                width={width}
                height={height}
            >
            </canvas>
        </>
    );
});

Upvotes: 1

Views: 1199

Answers (2)

fjplaurr
fjplaurr

Reputation: 1950

From documentation:

Even if an ancestor uses React.memo or shouldComponentUpdate, a rerender will still happen starting at the component itself using useContext.

Therefore, the component wil rerender because of the fact we are using useContext.

There is a discussion in github where 3 solutions are propoosed for this case. Here is the link.

Upvotes: 1

Ricardo Gonzalez
Ricardo Gonzalez

Reputation: 1879

It looks like you are incrementing the count here:

 Count: {count.current++}

If you are only displaying a value you should not mutate it on the render.

You can handle this increment in other part of the code, maybe write a method that increment your counter and just apply it when its necessary. Other solution is to create a useEffect that will handle this counter.

In this case you are incrementing your value very time because you are making this operation on the render method.

Upvotes: 0

Related Questions