Himanshu Ahuja
Himanshu Ahuja

Reputation: 227

useState Hook Renders entire component on setState

In the below code, I have used 2 "useState" hooks. Whenever I call the "setState" function of any one of these hooks, the whole component is re-rendered(Check "console.log" statements). I want if I call "setState" for one variable, only the element associated with that variable should render, rather the entire component

Code Snippet:

const App = () => {

  const [count, setCount] = React.useState(0)
  const [count2, setCount2] = React.useState(0)

  return (
    <SafeAreaView>
      <TouchableOpacity onPress={() => setCount(count => count + 1)}>
        {console.log('Counter 1')}
        <Text>{count}</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={() => setCount2(count2 => count2 + 1)}>
        {console.log('Counter 2')}
        <Text>{count2}</Text>
      </TouchableOpacity>
    </SafeAreaView>
  );
};

Upvotes: 0

Views: 1057

Answers (1)

Hend El-Sahli
Hend El-Sahli

Reputation: 6752

Render each Text in a stand-alone component ... This way whenever each Counter component receives a new-prop .. it will re-render.

 function FirstCounter ({ count }) {
  console.log('FirstCounter', count);
  return (  
    <Text>{count}</Text>
  );
}

export default React.memo(FirstCounter);

function SecondCounter ({ count }) {
  console.log('SecondCounter', count);
  return (  
    <Text>{count}</Text>
  );
}

export default React.memo(SecondCounter);

function App() {
  /** state is it was */
  const [count, setCount] = React.useState(0);
  const [count2, setCount2] = React.useState(0);

  return (
    <SafeAreaView>
      <TouchableOpacity onPress={() => setCount(count => count + 1)}>
        <FirstCounter count={count} />
      </TouchableOpacity>
      <TouchableOpacity onPress={() => setCount2(count2 => count2 + 1)}>
        <SecondCounter count={count2} />
      </TouchableOpacity>
    </SafeAreaView>
  );
}

Upvotes: 2

Related Questions