Is it possible to import states and functions on a functional React Component to make it cleaner?
Here's how my code looks like as of the moment:
import React from 'react'
//more imports...
const Dashboard = () => {
const [] = useState()
//more states here..
const fetch = asycn () => {
//more code..
}
//more functions here...
return (
<>
</>
)
}
However, I would like to know if it is possible to separate all states and functions so that my react component file would just look like this:
import React from 'react'
//more imports...
//import states and functions
const Dashboard = () => {
return (
<>
</>
)
}
are there any other way to import it for me to use the data inside this component? (other than custom hooks to minimize my code)
CodePudding user response:
You might want to look into Redux, It is used for centeralizing state in a global store which can be accessed throughout the applicaiton.
However you will need to use a hook, useSelector() to acess the state, and useDispatch() to dispatch a new state.
You can also pass down state through props from at parent component,
const Dashboard = ({state, setState}) => {
return (
<>
</>
)
}
However, then the parent component will have many const [state, setState] = useState()
CodePudding user response:
for complex state's and what you are describe you need to use redux. https://redux.js.org/introduction/examples
for local and simple state useState is the optimally option
I hope my answer guided you