question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Tips] Atoms can be created on demand

See original GitHub issue

Atoms can be created at anytime, like event callbacks and useEffect, or in promises.

Here’s a simple Todo example.

import * as React from "react";
import { useState, FormEvent } from "react";
import { Provider, atom, useAtom, PrimitiveAtom } from "jotai";

type Todo = {
  title: string;
  completed: boolean;
};

const TodoItem: React.FC<{
  todoAtom: PrimitiveAtom<Todo>;
  remove: () => void;
}> = ({ todoAtom, remove }) => {
  const [item, setItem] = useAtom(todoAtom);
  const toggleCompleted = () => {
    setItem((prev) => ({ ...prev, completed: !prev.completed }));
  };
  return (
    <li>
      <label>
        <input
          type="checkbox"
          checked={item.completed}
          onChange={toggleCompleted}
        />
        <span style={{ textDecoration: item.completed ? "line-through" : "" }}>
          {item.title}
        </span>
        {item.completed && <button onClick={remove}>Remove</button>}
      </label>
    </li>
  );
};

const todosAtom = atom<PrimitiveAtom<Todo>[]>([]);

const TodoList: React.FC = () => {
  const [title, setTitle] = useState("");
  const [todos, setTodos] = useAtom(todosAtom);
  const addTodo = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const todoAtom = atom<Todo>({ title, completed: false });
    setTodos((prev) => [...prev, todoAtom]);
    setTitle("");
  };
  const removeTodo = (todoAtom: PrimitiveAtom<Todo>) => {
    setTodos((prev) => prev.filter((item) => item !== todoAtom));
  };
  return (
    <ul>
      {todos.map((todoAtom) => (
        <TodoItem
          key={todoAtom.key}
          todoAtom={todoAtom}
          remove={() => removeTodo(todoAtom)}
        />
      ))}
      <li>
        <form onSubmit={addTodo}>
          <input
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="Enter title..."
          />
        </form>
      </li>
    </ul>
  );
};

const App: React.FC = () => (
  <Provider>
    <TodoList />
  </Provider>
);

export default App;

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:9
  • Comments:16 (8 by maintainers)

github_iconTop GitHub Comments

3reactions
dai-shicommented, Sep 9, 2020

Hi @asfktz ! First off, let’s define terminologies:

  • atom config: The return value of atom(). It’s an object which never changes.
  • atom value: The return value of useAtom(...)[0]. It’s the real value stored in Provider.

The atom value is removed from the Provider when no components (precisely useAtom hook) use it any longer. This takes care of dependencies: If atomA depends on atomB, atomB value is removed only after atomA is removed.

The atom config is just an object, so it’s garbage collected by JS when there’ no reference to it.

For example, of you remove a todo, the garbage collector will kick in?

So, yes.

1reaction
asfktzcommented, Sep 9, 2020

Hmm…! I get it now Thanks @dai-shi

Read more comments on GitHub >

github_iconTop Results From Across the Web

Single Atoms, On Demand
It makes sense - if you want things to react, getting all the partners dissolved in some medium where they can roam around...
Read more >
Core — Jotai, primitive and flexible state management ...
Atoms can be created on demand ​​ If not, the atom would be re-created each time the component renders. You can create an...
Read more >
Atoms to Electric Current
Electrons can be made to move from one atom to another in a flow. One electron is attached and another electron is lost....
Read more >
The science of electricity - U.S. Energy Information ...
To understand electricity, some basic information about atoms is helpful. Atoms are the building blocks of the universe. Everything in the universe is...
Read more >
Jotai vs. Recoil: What are the differences?
Atomic features. Recoil allows you to create a state that could be shared between multiple components. It looks a lot like a regular...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found