Basically in class components we pre initialise state in constructor with initial values like below.
constructor(props){
super(props);
this.state = {
count: 0
}
}
But after hooks are introduced all the class components became functional components with state.
But my query is how can I pre initialise count state to 0 with hooks in React v16.7.0
Here's the documentation: https://reactjs.org/docs/hooks-state.html
The example in the documentation shows:
const [count, setCount] = useState(0);
The parameter passed in to useState (e.g. "0" in this case) is the initial value.
If you want to set initial state after loading data (fetch data from api) you can use "useEffect" in React hooks. it is equal to "componentWillReceiveProps" in class component. so when you set state value in useEffect make sure avoid infinity loop eg ..
const [count,setcount] = useState(0)
useEffect(()=>{
setcount(api.data.count) // api.data.count from api after update store
},[])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With