skip to Main Content

in this case, it will trigger render again when I call updateNumber(), so how can create the valuable that it is for saving data only?

function test() {
   const [cartNum, setCartNum] = useState(0);

  function updateNumber() {
    setCartNum(number +1);
  }
  return (
    <View style={{ flex: 1 }}>
       <TouchableOpacity onPress={updateNumber}>
          <Text>
            {Math.random()}
          </Text>
      </TouchableOpacity>
    </View>
  );
}

2

Answers


  1. Use the useRef hook

    Example below

    // Call on top of component 
    const number = useRef(0);
    
    const updateNumber = ()=>{
        number.current++;
    }
    
    Login or Signup to reply.
  2. There are 2 ways for it to update and not re render:

    // by using normal variables
    function test() {
       let number = 0;
    
      function updateNumber() {
        number++
      }
      return (
        <View style={{ flex: 1 }}>
           <TouchableOpacity onPress={updateNumber}>
              <Text>
                {Math.random()}
              </Text>
          </TouchableOpacity>
        </View>
      );
    }
    
    // or as carlos mentioned by using ref
    
    function test() {
       const number = useRef(0);
    
      function updateNumber() {
       number.current++;
      }
      return (
        <View style={{ flex: 1 }}>
           <TouchableOpacity onPress={updateNumber}>
              <Text>
                {Math.random()}
              </Text>
          </TouchableOpacity>
        </View>
      );
    }
    

    Hope it helps. feel free for doubts

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search