It is not so difficult. We know many compounds already with their formulas.
1) we know the valency of some elements already like hydrogen, fluorine, chlorine, oxygen, Sodium, potassium, bromine, carbon, nitrogen ....
2) from known valencies we can get the valency of the unknown ones, as the neutral elements, molecules and compounds have 0 total valency..
3) Ions have total valency = charge on them.
4) If you remember the position of the element in the periodic table or, if you know the group to which this element belongs, then you know the valency easily.
5) If you know the electronic configuration of the elements, (if this subject is already covered) then it is easier.
6) There is no difficulty with simple elements. But with Copper, Iron Fe, Phosphorus, Sulphur, Nitrogen - some compounds exist with them in multiple oxidation level and valencies. There comes some difficulty.
Remember like SO4 has 2 minus. NO3 has one -. This way too you can calculate the valency values.