Home > Software engineering >  How to set state a variable from another file in react
How to set state a variable from another file in react

Time:06-06

I have a state variable "day" in a "first file" declared like that :

const [day, setDay] = useState('');

trying to clean my code i have to move the code of "setDay" in another file that i call service where i want all the database stuff of my program.

my question is how to access to the setDay method from another file and be able to fill it with the result of my database. thanks by advance.

CodePudding user response:

This is called Lifting State Up its mentioned here in react docs.

CodePudding user response:

Generally, useState should be only called in the component.

If you want to have a centralized state file, then look at React Context or a state library like MobX.

If you just want to split the useState part of a component (that is only used in that one component) into another file, look at creating a custom hook.

CodePudding user response:

Create child component for changing day. This is where you will access setDay function that you pass from parent component

ChangeDay.js

export const ChangeDay = ({ onHandleDay }) => {
  return (
    <div className="App">
      <h2>Button below to change:</h2>
      <button onClick={() => onHandleDay("TUESDAY")}>CLICK ME</button>
    </div>
  );
};

Then inside App.js pass setDay to onHandleDay prop.

import { useState } from "react";
import { ChangeDay } from "./ChangeDay";

export default function App() {
  const [day, setDay] = useState("Monday");

  return (
    <div className="App">
      <h1>Hello {day}</h1>
      <ChangeDay onHandleDay={setDay} />
    </div>
  );
}

Working demo

  • Related