6

What are the advantages or disadvantages to declaring static variables in a React functional components within a useRef() hook vs. simply declaring them as an object property.

useRef Approach:

import React, { useRef } from "react";

const MyComponent = () => {

  const staticProp = useRef("Hello, World!");

  return (
    <div>{staticProp.current}</div>
  )
}

export default MyComponent;

Object Property Approach:

import React from "react";

const MyComponent = () => {

  return (
    <div>{MyComponent.staticPro}</div>
  )
}

MyComponent.staticProp = "Hello, World!";

export default MyComponent;

1 Answer 1

8

Refs are useful for mutable values bound to your component instances. They are similar to instance variables. If the variable is supposed to be static, you don't need refs. You can declare it as a property of your component function, or as a constant in the outer scope:

const staticProp = "Hello, World!";

const MyComponent = () => {
  return (
    <div>{staticProp}</div>
  )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.