tomdelahaba
tomdelahaba

Reputation: 1048

React keep ref in state, good or bad practise? How to get ref on some DOM element from another component

Hello I would like to ask, is it "good" (ok) or bad practise to store ref in parents state?

What I need:

Unfortunately, ComponentA is null and does not exist when the application starts. This component is initialized dynamically based on something else. If I create the ref and pass it through props in WRAPPER component, unfortunately it remains null. In ComponentA (when it is initialized) I can successfully reach the reference, unfortunately WRAPPER does not know about its initialization.

That is why I am thinking about instead of forwarding this ref, I think about forwarding state in which I would like to keep the reference. In ComponentA receive the ref and set the Ref. This is how WRAPPER will recognize the ref changed and than I should pass the ref to ComponentB in which I will be able to get the attributes.

Is there anything else (better solution) to solve this one?

Upvotes: 2

Views: 4733

Answers (2)

David I. Samudio
David I. Samudio

Reputation: 2693

TL;DR: use contexts to separate state, hooks, and elements' lifecycles:

import { createContext, useCallback, useContext, useState } from "react";

const App = () => {
  return (
    <div className="App">
      <ComponentA />
      <ComponentB />
    </div>
  );
};

export const AppContext = createContext(null);

const Wrapper = (props) => {
  // HOC with context
  const [data, setData] = useState("Nothing typed yet.");

  return (
    <AppContext.Provider value={{ data, setData }}>
      <App {...props} />
    </AppContext.Provider>
  );
};

const ComponentA = () => {
  const { setData } = useContext(AppContext);
  const handleChange = useCallback(
    (event) => {
      setData(event.target.value);
    },
    [setData]
  );
  return <input type="text" onChange={handleChange} />;
};

const ComponentB = () => {
  const { data } = useContext(AppContext);
  return (
    <>
      <h2>Start editing to see some magic happen!</h2>
      <h1>{data}</h1>
    </>
  );
};

Check it out here.

NL;PR: In React, state refers (no pun intended) to data values that can be serialized. Refs and other functions and other program references cannot be serialized. Doing so, breaks hydration.

Since both can be used as props, it causes confusion.

Upvotes: 0

Sullivan Tobias
Sullivan Tobias

Reputation: 152

store a ref into a state is totally alright if you need some re-render based on that one

Upvotes: 0

Related Questions