简体   繁体   中英

How can create the valuable in react native functional component and it doesn't trigger a re-render when update it?

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>
  );
}

Use the useRef hook

Example below

// Call on top of component 
const number = useRef(0);

const updateNumber = ()=>{
    number.current++;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM