Chunky Chunk
Chunky Chunk

Reputation: 17237

React Hooks Static Variables: Object Property vs useRef()

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;

Upvotes: 6

Views: 3067

Answers (1)

Pierre V.
Pierre V.

Reputation: 1625

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

Upvotes: 8

Related Questions