The oxidation state of an element in a compound is simply decided on the basis of electronegativity of other atoms. As the definition of oxidation state says
Oxidation state of an element in a given compound is the charged acquired by its atom on the basis of electronegativity of other atoms in the compound.
The basis of calculating oxidation number is that the more electronegative element acquires the negative charge and the less electronegative one acquires the positive charge. So in molecules in which hydrogen is less electronegetive it acquires a $+1$ charge while in molecules in which it is more electronegetive it will acquire a $+1$ charge ($1$ because it has the valency of $1$ and usually oxidation number does not exceed valency).
Let's understand it with the help of examples:
In the $\ce{HCl}$ molecule, $\ce{H}$ is less electronegetive that's why charge of $+1$,for the same reason,$+1$ in $\ce{H2O}$.
In the compound $\ce{ZnH2}$, hydrogen is more electronegetive so it will have a charge of $-1$, for similar reason $-1$ in $\ce{NaH}$.
Usually metals (that make metal hydrides) are less electronegetive than hydrogen, That's why we also say hydrogen has an oxidation state of $-1$ in metal hydrides.