1

Is it generally better to define a contract instance once, then pass it through your components like...

    class Parent extends React.Component{
      constructor(props){
        super(props);
        this.state={
          contract = new contract(contract.abi, contract.address)
          }
        }

      render() {
        return{
          <div>
            <Child contract={this.state.contract}/>
          </div>
        }
      }
    }
    class child extends React.Component{
      constructor(props){
        super(props);
      }

      async function = () => {
        //use this.props.library in here to call contract methods
      }

      render() {
        return{
          <div>
            <other stuff />
          </div>
        }
      }
    }

Or is it alright to define a new contract instance every time you need to use it?

    class Parent extends React.Component{
      constructor(props){
        super(props);
      }

      render() {
        return{
          <div>
            <Child />
          </div>
        }
      }
    }
    class child extends React.Component{
      constructor(props){
        super(props);
      }

      async function = () => {
        //use this.state.library in here to call contract methods
      }

      render() {
        return{
          <div>
            <other stuff />
          </div>
        }
      }
    }
1

It's okay to define a contract instance every time you need it, as the ABI and deployed address haven't changed, and your web3 library is only creating a Javascript object off-chain, not checking on-chain or doing anything slow over the network.

I think the efficiency difference is negligible, but if you can create your contract instance once and pass it around, it would also save you the trouble of passing your ABI and deployed address everywhere in the child components.

  • Thanks for your reply! I was mostly wondering about the efficiency. I wasn't sure if it was just personal preference, or if there was a best practice for instantiating a contract. – JarethRader Oct 15 at 15:07
  • You're welcome. In this case, the performance difference is not as important as the cognitive difference (simpler designs fit better into human memory and attention), so passing around one contract instance is better than passing around an ABI + address. – Paul Pham Oct 16 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.