In the Fiber node, the effects associated with the Fiber node are encoded in the node’s effectTag field. But a component can have multiple side effects, so how does React determine that multiple side effects are to be performed by a single field?

React uses bitwise or constructs a set of properties, such as:

  • 0b00000000100, indicating that Update side effects need to be performed
  • 0b00100000000Indicates that Snapshot side effects need to be performed

EffectTag defaults to 0. In updateClassInstance, use bitwise or add side effects identifiers

if (typeof instance.componentDidUpdate === 'function') {
    workInProgress.effectTag |= Update;
}
if (typeof instance.getSnapshotBeforeUpdate === 'function') {
    workInProgress.effectTag |= Snapshot;
}
Copy the code

For example, if our component has both Update and Snapshot side effects, the Fiber node’s effectTag would be

effectTag |= 0b00000000100
effectTag |= 0b00100000000
Copy the code

The binary representation of the effectTag is 0b00100000100, with bit 3 equal to 1 and bit 9 equal to 1.

In commitAllLifeCycles, determine whether side effects are needed by bit-by-bit

function commitAllLifeCycles(finishedRoot, ...) {
    while(nextEffect ! = =null) {
        const effectTag = nextEffect.effectTag;

        if (effectTag & (Update | Callback)) {
            const current = nextEffect.alternate;
            commitLifeCycles(finishedRoot, current, nextEffect, ...);
        }
    
        nextEffect = nextEffect.nextEffect;
    }
}
Copy the code

For example, if our effectTag is 0b00100000100 and we need to check if the third bit is set to 1, we use bitwise and judgment

0b00100000100 & 0b00000100100 // does not equal 0
0b00100000000 & 0b00000100100 / / equal to zero
Copy the code

The bitwise and rule is: 1 & 1 equals 1; 1 over 0 is 0; 0 and 1 is 0; 0 minus 0 is 0. If the third bit is not a 1, the sum will be 0.