Reputation: 758
I have start learning redux a few days ago and I want to combain it with react app , I found multiple ways to do that , but still looking for the best of them.
I-Method 1:
first of all , in normal cases I use state like this inside class :
class myclass extends Recat.Component{
constructor(){
super()
//initiale
this.state={
something :something
}
}
//change value
this.setstate({something:something});
//use of value
this.state.something
}
the problem in first case , I can't integrate hooks like
useState()
useDispatch()
useSelector()
with this first method you will need to use connect()
and call the props to combain the store.
II-Method 2:
when I want to use call redux and use these hooks functions in my app I found that I can't use it if I didn't remove class and change my component to this format :
const Myfunction=()=>{
//to call the value from store
const something = useSelector(state=>state.somthing)
//and to use state I use usestate
const [something,setsomething] = useState(' something ');
//and of course to change value
dispatch = useDispatch();
//as a callback
dispatch(action);
}
the first question is why hooks didn't work on the first example syntax?
another question is what is the best method to use to combain redux with react and why?
thanks in advance.
Upvotes: 1
Views: 32
Reputation: 819
Your first method uses a class component, which is not compatible with Redux Hooks. To interact with Redux with class components, you need to use connect
/mapStateToProps
.
https://react-redux.js.org/using-react-redux/connect-mapdispatch
Your second method uses a functional component, which is compatible with Redux Hooks.
https://react-redux.js.org/api/hooks
There is not really a "best" method, both are completely valid, however React is moving towards functional components in general so it would beneficial to lean towards this as well.
Upvotes: 2