I have an external module file Task.ts
which has the following:
const taskList: Task[] = [];
Class Task {
...
}
export { Task, taskList }
And taskList
is a list of Task
objects that is modified by the Task
class.
Then I have my main app.tsx
file. And I’m importing the list and the class like so:
import { Task, taskList } from "./Task"
So I’m just wondering if there is a way to link taskList
to a react state so that changes to taskList
through the Task
object will trigger a re-render. I’ve tried useEffect
and putting taskList
in the dependency array, but that hasn’t worked.
2
Answers
If
taskList
can be updated from outside the App component or its childrens then you have to handle an event somehow and trigger useEffect to run to get the updatedtaskList
array then update the state that holdstaskList
.I can think of emit a socket event each time you update
taskList
and listen for it fromuseEffect
in App this will make the component rerender with the updated data whentaskList
is updated.otherwise you can update your state each time you update
taskList
, make each method ofTask
not only do its work but also returningtaskList
so you can easely call it and update the state after each change.You can use
useState
and here is a simple example:The function
updateList
is responsible for modifying thetasks
state variable when a new task is added. It takes thenewTaskContent
as a parameter, creates a newTask
object with the provided content, and then updates thetasks
state variable by adding the new task to the existing list (taskList
) using the spread operator (…).the
tasks
will automatically re-render when the state variabletasks
is updated using thesetTasks
function.Here is a simplify using vanilla JavaScript, and in addition to the example below,
useState
takes care of re-rendering the objects when it changes.More about
useState
and re-rendering:ReactJS | How does React associate Hook calls with components?
Medium | React Hooks – Understanding Component Re-renders