When an animal grooms himself with his tongue it is inevitable that some hair will be ingested. Cats groom themselves and so do dogs.
Hairballs occur because hair acts a bit differently than most fiber that slides through the digestion process along with the food. Hair sometimes gets stuck along the way. Typically, the hair remains in the stomach and forms a ball after repeated contractions of the stomach coil it up. Then it gets just big enough for the body to decide it is a foreign object and has to go. The animal vomits it out.
Then sometimes the hair gets through the stomach and to the intestines clumping along the way. The hair lodges and blocks the intestine. So the animal gets "bound up" and may develop what appears to be diarrhea. What is really going on is the liquid waste is strained through the wad of hair, leaving a chunk of wrung out waste behind the hair plug. Usually the body is able to eventually move the hair out along with the rest of the waste material. But that can take a day or more, meanwhile the poor animal is uncomfortable and his owner becomes worried that he may be ill.
Many dogs with "chronic diarrhea" might be full of hair! What's to be done? So far there are no hairball remedies widely available for dogs. But we can do a few things to lessen the likelihood of doggy hairballs.
To start, there are common sense things like keeping plenty of water available for the dog to drink and offering food and treats that contain non hair style fiber. Examples of good doggy fiber are: most vegetables, whole grains, some fruits and nuts. Another common sense idea is exercise. Exercise keeps things moving.
Alas, there is only so much we can do.
Case in point. A dog of my acquaintance is of a breed in the herding group. Now, we all know that herders can be intense. And with intensity comes quirks. In short, this herder sometimes gets antsy. Even with exercise, water, fibrous food and a job to do, this dog sometimes feels the need to take comfort in chewing her foot. Hair ingestion occurs and the hairball cycle begins again.