Microgrids plays a vital role in the electrification of remote areas. Due to the diversity of energy resources in the microgrid, the optimal energy management of such systems has become a challenging task. A standard microgrid generation consists of diesel, biomass, and renewable resources like photovoltaics, wind turbines, etc. And thus, an optimal operation requires proper sizing and energy dispatch for generation units. The manuscript discusses the optimal energy management strategy for microgrids or hybrid systems. The first part determines the optimal capacity of energy resources, such as photovoltaic, wind turbines, diesel generators, biomass, and energy storage devices such as batteries, followed by optimal energy dispatch strategy based on demand response. Finally, the proposed optimization was tested with an example with different scenarios with a comprehensive discussion.