1

I am new to this community and react development and currently developing a app for learning react. I have found that my current implementation causes re renders in every state update. How to fix this issue?


import React, { useState } from "react";

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

  const handleIncrement = () => {
    setCount(count + 1);
  };

  const handleDecrement = () => {
    setCount(count - 1);
  };

  const handleReset = () => {
    setCount(0);
  };

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={handleIncrement}>Increment</button>
      <button onClick={handleDecrement}>Decrement</button>
      <button onClick={handleReset}>Reset</button>
    </div>
  );
};

export default Counter;

Searched solution on web

2 Answers2

0

The default behavior would be the one you just described. In most cases, when state updates, the component should re-render to see the update.

If you want to re-render a complex component only when the props change, you can use memo, like this:

import { memo } from 'react'

const Component = (props) => {
    // component logic
};

export default memo(Component);

In your case, your component should update when the state changes, because I assume you want to show the count in the h1 when it increases.

Alexxino
  • 557
  • 2
  • 16
0

Normally react should render the component every time the state is updated, but you can decide when to render something using useMemo.

import React, { useMemo, useState } from "react";

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

  
  //This part will be memorized
  const StaticBlock = useMemo(() => {
    const handleIncrement = () => {
      setCount(prevCount => prevCount + 1);
    };

    const handleDecrement = () => {
      setCount(prevCount => prevCount - 1);
    };

    const handleReset = () => {
      setCount(0);
    };
    
    return (
        <>
            <button onClick={handleIncrement}>Increment</button>
            <button onClick={handleDecrement}>Decrement</button>
            <button onClick={handleReset}>Reset</button>
        </>
    )
  }, [])

  return (
    <div>
      <h1>Counter: {count}</h1>
      {StaticBlock}
    </div>
  );
};

export default Counter;