Nomada
Nomada

Reputation: 373

Best way to store non-observable data in a React Stateless Component (with Hooks)

I'm using mobx-react / mobx-react-lite for state management

Using classes i can define a non observable idToDelete to store the clicked item id, open a Modal using an observable and when the user clicks "Delete", i know the item to delete. The id is "remembered" by the component trough the re-renders

    class Greeting extends React.Component {
      idToDelete = null;

      confirmDelete = id => {
        this.idToDelete = id;
        openConfirm = true;
      }

      closeModal = () => {
        openConfirm = true;
        this.idToDelete = null;
      }

      @observable
      openConfirm = false;
      render() {
        // List of items with delete button
        <button onClick=this.confirmDelete(id)>Delete</button>

        // Confirm Delete Modal

      }
    }

But in a stateless component the id will become null (the initialization value) on each re-render.

Using useLocalStore hook i can store observable values:

All properties of the returned object will be made observable automatically

But i dont want to re-render just because i am storing/changing the id.

Using React.React.createContext / useContext seems like a bit overkill to me (it's kind of private value and it is not relevant outside the component itself)

Is there a "local storage" way to achieve this? (without observable convertion)

What are best practices for this situation?

Upvotes: 2

Views: 1053

Answers (1)

johnny peter
johnny peter

Reputation: 4872

You can use the useRef hook to save the value. A change to this value will not trigger a re-render and the value will remain the same across renders unless you override it.

Its also explained in detail here

Yes! The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class.

eg:

import { useRef } from 'react';

const idToDelete = useRef("");

confirmDelete = id => {
    idToDelete.current = id;
}

closeModal = () => {
    idToDelete.current = null;
}

Also mind the catch, you need to use .current to access the data.

Upvotes: 3

Related Questions