Search code examples
javascriptjavareactjsecma

can we create static member in react?


in java we have static members which is same copy for all the instances, is there any ways to active same in react ,

i already solved the problem using redux., but i eagerly searching to solve the problem by using static members

in java

public class Cart {

    static int totalItemInCart = 0; 
}


class Order{

    static boolean pushToCart() {

        Cart.totalItemInCart += Cart.totalItemInCart+1;     
        return true;
    }
}

class CancelOrder{  

    static boolean removeFromCart() {

        Cart.totalItemInCart += Cart.totalItemInCart-1;     
        return true;
    }
}

class User {

    public static void main(String[] args) {

        Order.pushToCart(); // item added to cart
        Order.pushToCart(); // item added to cart
        CancelOrder.removeFromCart(); // one item removed from cart 

        // if print the count we will get totalItemInCart is 2 
        System.out.println("number of items in cart" + Cart.totalItemInCart);
    }

}

now i want do the same in react, is there any way we can access a class member in multiple instances.

in react as of now i only can access initial values

class App extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return <h1>Count : {new Count().state.count} </h1>;
  }
}

class Count extends Component{
  constructor(props) {
    super(props);
    this.state={
      count:0
    }
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

output will be

Count : {new Count().state.count}


Solution

  • Javascript (which react is based) is not a truly OOP like Java, it's a prototype type based language, So there is not a straight equivalent for class and static variables.

    In react for those global stuff we would use Redux for data or React.Context api for application global state.

    However with ES6 you can write class like syntax like these

    class Cart {
      static count = 0;
    
      add = () => {
        Cart.count++;
      };
      remove = () => {
        Cart.count--;
      };
    
      print = () => {
        console.log(Cart.count);
      };
    }
    

    which work pretty much like Java's class variables. you can try this example, notice on render, the value still the same one. https://codesandbox.io/s/wo62022jo5