This study presents the optimal design and operation of a proposed hybrid renewable energy system (HRES) for the electrification of a residential building in rural areas in Pakistan. The main contributions of this study are twofold. Firstly, it develops a size optimization model based on the particle swarm optimization (PSO) technique to determine the optimal configuration for two hybrid renewable energy systems (HRES), including both grid-tied and off-grid modes, integrating wind and photovoltaic (PV) systems with battery storage. The optimal configuration is determined by minimizing the levelized cost of electricity, using local meteorological and electricity load data, along with technical specifications of the main HRES components. Secondly, dynamic simulations of two HRES configurations are conducted, using MATLAB Simulink, ensuring the optimal energy balance between multiple energy sources and the load at each operation hour. To meet an annual electrical demand of 131.035 MWh, the grid-tied HRES yields 146.081 MWh annually, with solar contributing 68.85 MWh and wind 77.272 MWh. Conversely, the off-grid system generates 133.533 MWh annually, with solar and wind output power at 43.932 MWh and 89.601 MWh, respectively. The grid-tied system achieves an LCOE of approximately 0.29 $/kWh, with optimal wind turbine and PV capacities of 11 kW and 29 kW, respectively. While in off-grid configuration, the off-grid scenario exhibits an LCOE of 0.91 $/kWh, with optimal capacities of 10 kW for wind turbine, 20 kW for PV, and 2437.5 AH for batteries. The findings provide insights relevant to diverse locations, emphasizing the importance of local meteorological and geographical data. Multiple case studies ensure the robustness and applicability of the proposed system under varying conditions.