What are the advantages or disadvantages to declaring static variables in a React functional ponents 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;
What are the advantages or disadvantages to declaring static variables in a React functional ponents 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;
Share
Improve this question
asked Sep 30, 2019 at 22:31
Chunky ChunkChunky Chunk
17.2k17 gold badges91 silver badges165 bronze badges
1 Answer
Reset to default 8Refs are useful for mutable values bound to your ponent 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 ponent function, or as a constant in the outer scope:
const staticProp = "Hello, World!";
const MyComponent = () => {
return (
<div>{staticProp}</div>
)
}